Chinaunix首页 | 论坛 | 博客
  • 博客访问: 35069
  • 博文数量: 12
  • 博客积分: 105
  • 博客等级: 民兵
  • 技术积分: 155
  • 用 户 组: 普通用户
  • 注册时间: 2012-11-24 20:46
文章分类

全部博文(12)

文章存档

2014年(5)

2013年(3)

2012年(4)

我的朋友

分类: C/C++

2014-02-24 14:02:53

Linux c多线程编程时创建线程的函数:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);

给子线程传递参数要通过void *类型的arg参数,大多传递参数都是传递参数的地址例如:

点击(此处)折叠或打开

  1. void *thread_func(void *arg)
  2. {
  3.     int value = *(int*)arg;
  4.     return (void *)0;
  5. }

  6. int value;
  7. pthread_t pid = pthread_create(&pid, NULL, thread_func, &value);

但当value值会改变时,传递给thread_func的值可能就不是先前的值.
要避免参数改变,可以采取的一种方法是函数参数改为值传递,例如:


点击(此处)折叠或打开

  1. void *thread_func(void *arg)
  2. {
  3.     int value = (int)arg;
  4. }

  5. int value;

  6. pthread_t pid = pthread_create(&pid, NULL, thread_func, (void*)value);

阅读(1403) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~