您的位置:首页 > 编程语言 > C语言/C++

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

2012-09-04 12:15 405 查看
http://blog.csdn.net/lzx_bupt/article/details/6913039

经过前面的几个例子,是不是还少个线程创建时属性参数没有提到,见下文示例:

[cpp] view plaincopy

#include <iostream>

#include <pthread.h>

#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 status = 10 + *((int *)args);//将参数加10

pthread_exit((void*)status);//由于线程创建时候提供了joinable参数,这里可以在退出时添加退出的信息:status供主程序提取该线程的结束信息;

}

int main()

{

pthread_t tids[NUM_THREADS];

int indexes[NUM_THREADS];

pthread_attr_t attr;//要想创建时加入参数,先声明

pthread_attr_init(&attr);//再初始化

pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);//声明、初始化后第三步就是设置你想要指定线程属性参数,这个参数表明这个线程是可以join连接的,join功能表示主程序可以等线程结束后再去做某事,实现了主程序和线程同步功能,这个深层理解必须通过图示才能解释;参阅其他资料吧

for(int i = 0; i < NUM_THREADS; ++i)

{

indexes[i] = i;

int ret = pthread_create( &tids[i], &attr, say_hello, (void *)&(indexes[i]) );//这里四个参数都齐全了,更多的配置仍需查阅资料;

if (ret != 0)

{

cout << "pthread_create error: error_code=" << ret << endl;

}

}

pthread_attr_destroy(&attr);//参数使用完了就可以销毁了,必须销毁哦,防止内存泄露;

void *status;

for (int i = 0; i < NUM_THREADS; ++i)

{

int ret = pthread_join(tids[i], &status);//前面创建了线程,这里主程序想要join每个线程后取得每个线程的退出信息status;

if (ret != 0)

{

cout << "pthread_join error: error_code=" << ret << endl;

}

else

{

cout << "pthread_join get status: " << (long)status << endl;

}

}

}

编译运行 g++ -lpthread -o ex_join ex_join.cpp

结果:

[plain] view plaincopy

hello in thread 4

hello in thread 3

hello in thread 2

hello in thread 1

hello in thread 0

pthread_join get status: 10

pthread_join get status: 11

pthread_join get status: 12

pthread_join get status: 13

pthread_join get status: 14

体会一下join的功能吧
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: