• pthread_mutex_lock


    #include <pthread.h> 
    #include <unistd.h> 
    #include <string.h>
    #include <iostream>
     
    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("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); 
        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 = (node*)malloc(sizeof(struct node)); 
            p->n_number = i; 
            pthread_mutex_lock(&mtx);           
            p->n_next = head; 
            head = p; 
            pthread_cond_signal(&cond); 
            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; 

  • 相关阅读:
    315. 计算右侧小于当前元素的个数
    55. 跳跃游戏
    <leetcode c++>72. 编辑距离
    "NTLDR is missing"和"NTLDR is compressed"的解决办法
    Windows Live Mail不能发送图片附件的2种解决方法
    【】使用word2010同步更新自己在不同网站的博客
    新浪博客测试
    【】引用 CSS行高line-height属性理解及应用
    "NTLDR is missing"和"NTLDR is compressed"的解决办法
    排序算法-冒泡排序(javascript)
  • 原文地址:https://www.cnblogs.com/greencolor/p/2221547.html
Copyright © 2020-2023  润新知