Linux 如何在 C 的多线程中使用互斥量

How to use mutex in multithreading with C on Linux

我如何使用 pthead_create() 在 C 中创建两个线程,但第一个打印 'h' 和 'o',第二个打印 'ell',并且结果是 'hello' 。我们如何使用 pthread_mutex_lock 和解锁而不使用任何 sleep() 来解决这个问题。请帮忙 。这就是我所做的,但有时它无法按预期工作。

#include <stdio.h>
#include <pthread.h>

pthread_t th[2];
pthread_mutex_t l1,l2;

void *print1(){
    pthread_mutex_lock( &l1 );
    printf("h");
    pthread_mutex_unlock( &l1 );
    pthread_mutex_lock( &l2 );
    printf("o");
    pthread_mutex_unlock( &l2 );
    return NULL;
}
void *print2(){
    pthread_mutex_lock( &l2 );
    printf("ell");
    pthread_mutex_unlock( &l2 );
    return NULL;
}
int main(){
    pthread_create(&th[0],NULL,print1,NULL);
    pthread_create(&th[1],NULL,print2,NULL);
    pthread_join(th[0],NULL);
    pthread_join(th[1],NULL);
    printf("\n");
    return 0;
} 

互斥体提供互斥,而不是排序。您需要添加更多或不同的东西来控制线程之间的相对操作顺序。为此,通常伴随互斥锁的是条件变量。您可以使用一个互斥量、一个条件变量和一个常规共享变量来完成您的工作。或者,一对信号量可以很好、干净地处理您的特定工作。

如果您可能使用的唯一同步对象是互斥体,那么您可以尝试不使用 CV 的互斥体/CV 方法。无论有无 CV,这里的关键是要有一个共享变量,以某种方式指示轮到哪个线程。每个线程都尝试锁定互斥锁。成功时,线程会检查共享变量以查看是否轮到该线程 运行,如果是,它会执行适当的工作,然后释放互斥体。如果一个线程锁定了互斥锁并发现 没有轮到 它,那么它释放互斥锁并循环回去重试。这里的问题是线程有可能在没有被调度的情况下运行无限长的时间,这就是在混合地址中添加条件变量的原因。