linux c线程条件变量示例

2021-08-22  本文已影响0人  一路向后

1.源码实现

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>

/*让线程2先于线程1执行*/
pthread_mutex_t lock;
pthread_cond_t cond;

void *thread_1(void *data)
{
    pthread_mutex_lock(&lock);
    pthread_cond_wait(&cond, &lock);
    printf("%s\n", __func__);
    pthread_mutex_unlock(&lock);
}

void *thread_2(void *data)
{
    pthread_mutex_lock(&lock);
    printf("%s\n", __func__);
    pthread_mutex_unlock(&lock);

    sleep(6);

    pthread_cond_signal(&cond);
}

int main()
{
    pthread_t tid[2];

    pthread_mutex_init(&lock, NULL);
    pthread_cond_init(&cond, NULL);

    pthread_create(&tid[0], NULL, thread_1, NULL);
    pthread_create(&tid[1], NULL, thread_2, NULL);

    sleep(1);

    //pthread_mutex_unlock(&lock);
    pthread_mutex_destroy(&lock);
    pthread_cond_destroy(&cond);

    pthread_join(tid[0], NULL);
    pthread_join(tid[1], NULL);

    return 0;
}

2.编译源码

 $ gcc -o example example.c -lpthread

3.运行及其结果

$ ./example
thread_2
thread_1
上一篇 下一篇

猜你喜欢

热点阅读