我有一个麻烦传递一个结构指针到一个函数,因为我有点与这些指针和引用混淆。我想修改thread_start
函数的thread.thread_num
值。线程结构作为函数参数C
#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: %i\n", my_data->thread_num);
my_data->thread_num=4;
printf("num T: %i\n", 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: %i\n",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, NULL, thread_start, (void *)&thread[i]);
printf("num %i: %i\n",i,thread[i]->thread_num);
}
pthread_exit(NULL);
return 0;
}
有什么想法?
线程是异步的。 –
你应该看看thread.join()。顺便说一句,该列表似乎缺少一个'}'作为'main'中'for'循环的一部分。 – KeithSmith
struct thread pthread_data [5]; – qwr