美文网首页
linux c线程条件变量示例

linux c线程条件变量示例

作者: 一路向后 | 来源:发表于2021-08-22 19:25 被阅读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

相关文章

  • linux c线程条件变量示例

    1.源码实现 2.编译源码 3.运行及其结果

  • pthread_cond_t条件变量

    Linux下C编程的条件变量: 条件变量是线程中的东西,就是等待某一条件的发生,和信号一样。 用法 条件变量使我们...

  • 线程

    简单线程 带参线程 最大线程数 mutex c++版本 纯c++版本 纯c版本 条件变量(condition) 信...

  • Linux线程同步

    Linux下提供了多种方式来处理线程同步,最常用的是互斥锁、条件变量和信号量。 Linux线程同步-----互斥锁...

  • 线程同步与互斥

    Linux--线程编程 多线程编程-互斥锁 线程同步与互斥 互斥锁 信号量 条件变量 互斥锁 互斥锁的基本使用...

  • Linux C 线程的互斥锁和条件变量

    这里简单的做了一个生产消费的案例,方便记忆

  • channel使用场景:条件变量(condition varia

    条件变量(condition variable)类型于 POSIX 接口中线程通知其他线程某个事件发生的条件变量,...

  • Linux 中的线程局部存储(1)

    在Linux系统中使用C/C++进行多线程编程时,我们遇到最多的就是对同一变量的多线程读写问题,大多情况下遇到这类...

  • Linux线程局部变量实现

    Linux线程局部变量实现 什么是线程局部变量,就是每个线程各自拥有一个的变量;比如errno,是每个线程各自拥有...

  • 多线程-volatile

    volatile作用: 使多个线程间变量可见。 线程变量不可见的示例: 运行结果,卡死不动: 解决办法: vola...

网友评论

      本文标题:linux c线程条件变量示例

      本文链接:https://www.haomeiwen.com/subject/iadhiltx.html