您的位置:首页 > 运维架构

pthread_cleanup_push/pop

2015-06-29 13:27 423 查看
notes:

pthread_cleanup_push

pthread_cleanup_pop

注意清理处理程序是按照与它们安装时相反的顺序被调用的。

#include <pthread.h>

#include <unistd.h>

static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;

static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

struct node {

int n_number;

struct node *n_next;

}

*head=NULL;

/*thread_func*/

static void cleanup_handler (void *arg)

{

printf("cleanuo handler of second thread\n");

free (arg);

(void) pthread_mutex_unclock(&mtx);

}

static void *thread_func(void *arg)

{

struct node *p=NULL;

pthread_cleanup_push(cleanup_handler,p);

while (1) {

//the mutex assure pthread_cond_wait concurrent

pthread_mutex_lock(&mtx);

while (head==NULL) {

//pthread_cond_wait is perfect, why add while (head==NULL)? because pthread_cond_wait thread might be wake up by accident,if head != NULL at that time, that is not what we want. at that moment, should let thread go on
enter pthread_cond_wait

//pthread_cond_wait will first unlock before pthread_mutex_lock lock mtx,then block in wait queue sleep ,till was wake up again (most ,wait conditon is true to wake up ,after wake up, the process first lock pthread_mutex_lock(&mtx);
read resource again

//block --->unlock ---->wait () return--->lock

//mutex_lock-->cond_wait(unlock metex and wait) ---->signal(wake up)--->mutex_lock(reback mutex_lock)

pthread_cond_wait(&cond,&mtx);

}

p=head;

head=head->n_next;

printf("Got %d from front of queue\n",p->n_number);

free(p);

//criticla data operater finish, release lock

pthread_mutex_unlock(&mtx);

}

pthread_cleanup_pop(0);

return 0;

}

int main(void)

{

pthread_t tid;

int i;

struct node *p;

//child thread wait resource all the time .as if product and consume. but these consume may be many consumers ,not only support nomal singal consumer, but model is simple ,but is strong

pthread_create(&tid,NULL,thread_func,NULL);

for (i=0;i<10;i++) {

p = malloc(sizeof(struct node));

p->n_number=i;

//need operate head critical resource ,first add lock

pthread_mutex_lock(*mtx);

p->n_next=head;

head=p;

pthread_cond_signal(&cond);

//unlcok

pthread_mutex_unlock(&mtx);

sleep (1);

}

printf("thrad 1 wanna end the line .so cancel thead 2\n");

// pthread_cancel ,have axtra explanation, it terminal child thread in external. child thred can canel in the latest . exit thread. in our code ,the latest cancel is pthread_cond_wait .about cancel point info ,please google
if you are interested for it

pthread_cancel(tid);

pthread_join(tid,NULL);

printf("All done--exiting \n");

return 0;

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