- #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;
-
- static void cleanup_handler(void *arg)
- {
- printf("Cleanup handler of second thread./n");
- free(arg);
- (void)pthread_mutex_unlock(&mtx);
- }
- static void *thread_func(void *arg)
- {
- struct node *p = NULL;
-
- pthread_cleanup_push(cleanup_handler, p); // 防止在获取锁之后,程序崩溃,引起的锁没有释放。加上这个之后,崩溃会调用到cleanup_handler
- while (1) {
- pthread_mutex_lock(&mtx);
- while (head == NULL) {
- pthread_cond_wait(&cond, &mtx);
-
- }
- p = head;
- head = head->n_next;
- printf("Got %d from front of queue/n", p->n_number);
- free(p);
- pthread_mutex_unlock(&mtx);
- }
- pthread_cleanup_pop(0);
- return 0;
- }
-
- int main(void)
- {
- pthread_t tid;
- int i;
- struct node *p;
- pthread_create(&tid, NULL, thread_func, NULL);
-
- for (i = 0; i < 10; i++) {
- p = malloc(sizeof(struct node));
- p->n_number = i;
- pthread_mutex_lock(&mtx);
- p->n_next = head;
- head = p;
- pthread_cond_signal(&cond); //pthread_cond_signal应该写在锁里边,如果写在锁外边的话,可能会有别的线程抢占到锁。但是,也有这种情况,就是pthread_cond_wait唤醒,获取锁,发现pthread_cond_signal还没有释放锁,进而继续进入休眠状态。需要测试
- pthread_mutex_unlock(&mtx);
- sleep(1);
- }
- printf("thread 1 wanna end the line.So cancel thread 2./n");
- pthread_cancel(tid);
- pthread_join(tid, NULL);
- printf("All done -- exiting/n");
- return 0;
- }
posted @
2018-08-20 21:17
caopf
阅读(
83)
评论()
编辑
收藏
举报