线程结构作为函数参数C

 小马哥 发布于 2023-02-11 20:02

我在将结构指针传递给函数时遇到了麻烦,因为我对这些指针和引用有点困惑.我想修改函数的thread.thread_numthread_start.

#include 
#include  //malloc, free
#include 

#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; ithread_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;
}

有什么想法吗?

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有