您的位置:首页 > 其它

初识pthread(二)-线程管理之线程同步入门(阻塞和分离式线程)

2015-02-25 17:51 405 查看
在上一篇博文中,我们提到了pthread_attr_t *attr这个变量,但我们并没有真正使用它,现在我们将初步揭秘它的神奇作用,本节聚焦:

pthread_join (threadid,status) ;

[b] pthread_detach (threadid) ;[/b]

[b][b] pthread_attr_setdetachstate (attr,detachstate)
[/b][/b]

[b][b][b] pthread_attr_getdetachstate (attr,detachstate)
[/b][/b][/b]

对于线程的同步,最简单安全的方式是阻塞(join),线程也分为阻塞式(joinable)线程和分离式(detachable)线程,最近的POSIX草案规定一个线程默认设为阻塞式(joinable),我们在pthread中可以使用attr变量来设定一个线程的类别(is
joinable)。

[b] 关于attr的使用,我们分为四个步骤:[/b]

[b] ①声明pthread_attr_t attr;[/b]

[b] ②初始化attr pthread_attr_init(&attr);[/b]

[b] ③设置线程类别 pthread_attr_setdetachstate(&attr,detachstatus);[/b]

[b] ④线程creat完毕后释放attr pthread_attr_destroy(&attr);[/b]

detachstatus的取值为PTHREAD_CREATE_JOINABLE/PTHREAD_CREATE_DETACHABLE,分别对应阻塞/分离类线程。

如果一个线程thread为阻塞式(joinable),那么我们就可以在其他线程中使用pthread_join(&thread,&status)来阻塞自身等待thread(joinable)结束,比如在线程1中调用pthread_join(&thread2,&status);将会阻塞线程1直到线程2结束。需要注意的是,一个线程可以对多个线程阻塞,但一个线程不能被多个线程阻塞,比如在thread1中调用pthread_join(&thread2,&status2);pthread_join(&thread3,&status3);pthread_join(&thread4,&status4)是可以的;但是分别在thread2、thread3、thread4中pthread_join(&thread1,&status);是不可以的。

如果一个线程thread是分离式(detachable),那么我们就可以在创建它之后继续其他工作,它所占用的资源将会在线程函数结束或main()结束时自动释放。

新手要牢记的一点是:如果一个线程thread为阻塞式(joinable),那么我们必须要在后文对其阻塞(join),否则即使thread的工作完全做完也不会释放自身所占用的系统资源,除非我们利用pthread_detach(&thread)强行使其转化为分离式。

#define HAVE_STRUCT_TIMESPEC 1
#define NUM 10
#include<pthread.h>
#include<iostream>
using namespace std;
struct userdata
{
int thread_index;
int data;
};
void *thread_func(void *data)
{
userdata * localdata = (userdata *)data;
for (int i = 0; i < 5; i++)
{
cout << "thread" << localdata->thread_index << ":" << localdata->data << endl;
localdata->data++;
}
//we always have pthread_exit in the end of thread
pthread_exit(NULL);
return NULL;
}
int main(void)
{
//first,we should allocate the pthread_t ourseleves;
pthread_t thread[NUM] ;
//declare and allocate attr;
pthread_attr_t *attr = nullptr; pthread_attr_init(attr);
pthread_attr_setdetachstate(attr, PTHREAD_CREATE_JOINABLE);
//define userdata
userdata data[NUM];
//create thread
for (unsigned char i = 0; i < 10; i++)
{
data[i].data = 0; data[i].thread_index = i;
if (int rc = pthread_create(&thread[i], attr, thread_func, &data[i]))
{
cout << "create thread erro:" << rc << endl;
}
pthread_join(thread[i], NULL);
}
//we free the attr just after creat the thread
pthread_attr_destroy(attr);
//some clean
pthread_exit(NULL);
}


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