线程结构作为函数参数C
发布时间:2020-12-16 09:49:20 所属栏目:百科 来源:网络整理
导读:我在将结构指针传递给函数时遇到了麻烦,因为我对这些指针和引用有点困惑.我想修改thread_startfunction中的thread.thread_num值. #include stdio.h#include stdlib.h //malloc,free#include pthread.h#define N 5// void *malloc(size_t);struct thread { pt
|
我在将结构指针传递给函数时遇到了麻烦,因为我对这些指针和引用有点困惑.我想修改thread_startfunction中的thread.thread_num值.
#include <stdio.h>
#include <stdlib.h> //malloc,free
#include <pthread.h>
#define N 5
// void *malloc(size_t);
struct thread {
pthread_t thread_id;
int thread_num;
// int thread_sum;
};
void *thread_start(void *thread)
{
struct thread *my_data;
my_data = (struct thread *)thread;
printf("num T: %in",my_data->thread_num);
my_data->thread_num=4;
printf("num T: %in",my_data->thread_num);
return NULL;
}
int main(int argc,char *argv[])
{
int i;
struct thread pthread_data;
struct thread *thread = &pthread_data;
thread->thread_num=2;
pthread_create(&thread->thread_id,NULL,thread_start,(void *)&thread);
printf("num: %in",thread->thread_num);
pthread_exit(NULL);
return 0;
}
但打印主体的价值不会改变(2). 然后我想创建一个线程结构数组,但我不知道究竟是怎么做到的: int main(int argc,char *argv[])
{
int i;
struct thread pthread_data;
struct thread *thread[N-1] = &pthread_data; // I don't know how to manage this.
for(i=0; i<N; i++)
{
thread->thread_num=i;
pthread_create(&thread[i]->thread_id,(void *)&thread[i]);
printf("num %i: %in",i,thread[i]->thread_num);
}
pthread_exit(NULL);
return 0;
}
有什么想法吗? 解决方法
我建议你阅读
http://www.advancedlinuxprogramming.com/alp-folder/alp-ch04-threads.pdf
在这里你想要的是: #define N 5
typedef struct thread {
pthread_t thread_id;
int thread_num;
// int thread_sum;
} ThreadData;
void *thread_start(void *thread)
{
ThreadData *my_data = (ThreadData*)thread;
//there is no guarantee that prints will be in order
// we will use its initial thread->num,cause it differs for each thread
//plus you will see how threads will behave
int order=my_data->thread_num;
printf("%i) before num T: %in",order,my_data->thread_num);
my_data->thread_num=4;
printf("%i) after assignment num T: %in",char *argv[])
{
int i;
ThreadData thread[N];
for(i=0; i<N; i++)
{
thread[i].thread_num=i;
pthread_create(&(thread[i].thread_id),(void *)(thread+i));
}
//wait for all threads
for (i = 0; i < N; i++)
pthread_join(thread[i].thread_id,NULL);
//print results of each thread
for (i = 0; i < N; i++)
printf(" %i)thread: number %in",thread[i].thread_num);
return 0;
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
