c - 线程结构作为函数参数 C

标签 c multithreading struct

我在将结构指针传递给函数时遇到问题,因为我对那些指针和引用有点困惑。我想修改 thread_start 函数中的 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: %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;
}

但是打印 main 的值没有改变 (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;
}

有什么想法吗?

最佳答案

我推荐你阅读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: %i\n",order, my_data->thread_num);
   my_data->thread_num=4;
   printf("%i) after assignment num T: %i\n",order ,my_data->thread_num);

   return NULL;
}

int main(int argc, char *argv[])
{
   int i;
   ThreadData thread[N]; 
   for(i=0; i<N; i++)
   {
      thread[i].thread_num=i;
     pthread_create(&(thread[i].thread_id), NULL, thread_start, (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 %i\n",i,thread[i].thread_num);
   return 0;
}

关于c - 线程结构作为函数参数 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20480529/

相关文章:

c++ - 游戏引擎 : How to transpose Variables from structs: Coding practices

c - 我在重新定义 "fptr"时遇到问题

c - 为什么我必须使用 close() 来关闭文件?

python - 在 Python 中使用线程时需要注意的注意事项?

c - 在 C 中将双指针作为参数传递

reflection - 在运行时解析传递给函数的结构

c++ - C/C++ 中的领域特定语言,这是 Kosher 吗?

复制包含长整数的字符串

java - 查询 Google App Engine 数据存储区时出现并发问题

c# - 应用程序.DoEvents();