c/c++: 多线程编程基础讲解(三)

转载地址 ::http://blog.csdn.net/lzx_bupt/article/details/6910632


线程会创建了,如何在线程调用函数时,传入参数呢?则应如下所示:

#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




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值