首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在Linux C上同步两个线程?

在Linux C上同步两个线程可以使用互斥锁(Mutex)和条件变量(Condition Variable)来实现。

互斥锁是一种同步原语,用于保护共享资源,确保在同一时间只有一个线程可以访问该资源。在C语言中,可以使用pthread库提供的互斥锁相关函数来操作互斥锁。常用的函数有pthread_mutex_init、pthread_mutex_lock、pthread_mutex_unlock和pthread_mutex_destroy。

条件变量用于线程之间的通信和同步。它允许一个线程等待另一个线程满足某个条件后再继续执行。在C语言中,可以使用pthread库提供的条件变量相关函数来操作条件变量。常用的函数有pthread_cond_init、pthread_cond_wait、pthread_cond_signal和pthread_cond_destroy。

下面是一个示例代码,演示了如何在Linux C上同步两个线程:

代码语言:txt
复制
#include <stdio.h>
#include <pthread.h>

pthread_mutex_t mutex;
pthread_cond_t cond;
int sharedData = 0;

void* thread1(void* arg) {
    pthread_mutex_lock(&mutex);
    while (sharedData < 10) {
        // 等待条件变量满足
        pthread_cond_wait(&cond, &mutex);
    }
    printf("Thread 1: sharedData = %d\n", sharedData);
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
}

void* thread2(void* arg) {
    pthread_mutex_lock(&mutex);
    sharedData = 10;
    // 发送信号通知等待的线程条件已满足
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
}

int main() {
    pthread_t t1, t2;
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);

    pthread_create(&t1, NULL, thread1, NULL);
    pthread_create(&t2, NULL, thread2, NULL);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    return 0;
}

在上述代码中,我们创建了两个线程t1和t2。线程t1等待条件变量满足后打印sharedData的值,而线程t2在修改sharedData后发送信号通知t1条件已满足。通过互斥锁和条件变量的配合,实现了线程之间的同步。

这里推荐腾讯云的云服务器(CVM)产品,它提供了高性能、可靠稳定的云服务器实例,适用于各种应用场景。您可以通过以下链接了解更多信息:https://cloud.tencent.com/product/cvm

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

考点总结:互联网校招技术岗都考些什么?数据结构算法游戏 + 场景c++面向对象javaJVMSpringandroid数据库计网线程安全linux前端询问面试官

数据结构 红黑树 pk 平衡二叉树 hash表处理冲突的方法 算法 手写 最长无重复字符子串 链表的增、删、查、逆序 数组实现队列,要求可以动态扩展,保证较高的空间利用率(即pop出队的空间可以重复利用) 思路 有序数列找最先重复的数? 无序数列? 不用辅助内存,交换两个数(异或,加和) 根据起点、终点查询地铁路线?得到路径后如何判断某个节点是否是换乘站? LRU缓存实现 快排复杂度?什么时候最坏?如何避免最坏?如何优化快排? x轴上有n个点,已知每个点的位置p和速度v(正表示向右,负表示向左),每当两个点

07
领券