c/c++: 多线程编程基础讲解(三)
2011-10-27 14:53
417 查看
线程会创建了,如何在线程调用函数时,传入参数呢?则应如下所示:
编译、运行,结果如下:
是否发现了问题?对,i的值没有输出预想的结果,这是因为多线程造成的,主进程在i还未赋值时,线程已经开始跑啦!~
那么下面代码是正确的:
编译、运行:(源程序去掉了打印线程id的废话)
#include <iostream> #include <pthread.h> using namespace std; #define NUM_THREADS 5 void* say_hello(void* args) { int i = *((int*)args);//对传入的参数进行强制类型转换,由无类型指针变为整形数指针,然后再读取; cout << "hello in " << i << endl; } int main() { pthread_t tids[NUM_THREADS]; cout << "hello in main..." << endl; for(int i = 0; i < NUM_THREADS; ++i) { int ret = pthread_create(&tids[i], NULL, say_hello, (void *)&i);//传入的时候必须强制转换为void* 类型,即无类型指针 cout << "Current pthread id =" << tids[i] << endl;//这里学会使用tids数组打印创建的进程id信息; if (ret != 0) { cout << "pthread_create error: error_code=" << ret << endl; } } pthread_exit(NULL); }
编译、运行,结果如下:
Current pthread id =139671233451792 Current pthread id =139671222961936 Current pthread id =139671212472080 Current pthread id =139671201982224 Current pthread id =139671191492368 hello in 4196496 hello in 4196496 hello in 4196496 hello in 4196496 hello in 4196496
是否发现了问题?对,i的值没有输出预想的结果,这是因为多线程造成的,主进程在i还未赋值时,线程已经开始跑啦!~
那么下面代码是正确的:
#include <iostream> #include <pthread.h> using namespace std; #define NUM_THREADS 5 void* say_hello(void* args) { cout << "hello in thread " << *((int *)args) << endl; } int main() { pthread_t tids[NUM_THREADS]; int indexes[NUM_THREADS];//用个数组来保存i的值,就不会变了 for(int i = 0; i < NUM_THREADS; ++i) { indexes[i] = i;//先保存i的值,在调用线程就不会出现问题了 int ret = pthread_create( &tids[i], NULL, say_hello, (void *)&(indexes[i]) ); if (ret != 0) { cout << "pthread_create error: error_code=" << ret << endl; } } for (int i = 0; i < NUM_THREADS; ++i) pthread_join(tids[i], NULL); }
编译、运行:(源程序去掉了打印线程id的废话)
[cpp@node2 pthread]$ ./ex_create_args_ok hello in thread 3 hello in thread 4 hello in thread 2 hello in thread 1 hello in thread 0
相关文章推荐
- c/c++: 多线程编程基础讲解(二)
- c/c++: 多线程编程基础讲解(四)
- c/c++: 多线程编程基础讲解(五)
- c/c++: 多线程编程基础讲解(六)
- c/c++: 多线程编程基础讲解(一)
- c/c++: 多线程编程基础讲解(六)
- c/c++: 多线程编程基础讲解(五)
- c/c++: 多线程编程基础讲解
- c/c++: 多线程编程基础讲解(一)
- c/c++: 多线程编程基础讲解
- c/c++: 多线程编程基础讲解(二)
- c/c++: 多线程编程基础讲解(三)
- c/c++: 多线程编程基础讲解(二)
- c/c++: 多线程编程基础讲解(四)
- c/c++: 多线程编程基础讲解(五)
- c/c++: 多线程编程基础讲解(六)
- c/c++: 多线程编程基础讲解(四)
- c/c++: 多线程编程基础讲解(一)
- c/c++: 多线程编程基础讲解(三)
- c/c++: 多线程编程基础讲解(一)