如何在Linux上用C进行多线程处理时使用互斥

如何在Linux上用C进行多线程处理时使用互斥,c,linux,mutex,C,Linux,Mutex,如何使用pthead_create()在C中创建两个线程,但第一个线程打印'h'和'o',第二个线程打印'ell',结果是'hello'。我们如何使用pthread_mutex_lock and unlock解决这个问题,而不使用任何sleep()。请帮忙。这就是我所做的,但有时并不像预期的那样有效 #include <stdio.h> #include <pthread.h> pthread_t th[2]; pthread_mutex_t l1,l2; void

如何使用pthead_create()在C中创建两个线程,但第一个线程打印'h'和'o',第二个线程打印'ell',结果是'hello'。我们如何使用pthread_mutex_lock and unlock解决这个问题,而不使用任何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;
} 
#包括
#包括
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);
返回NULL;
}
void*print2(){
pthread_mutex_lock(&l2);
printf(“ell”);
pthread_mutex_unlock(&l2);
返回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”);
返回0;
} 

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


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

使用一对信号量(或者,如果宗教禁止信号量,则使用条件变量)。您好,我是初学者我不知道你说的信号量是什么意思你说的是互斥锁和解锁,因为我只想用互斥锁。你坚持使用不合适的工具来完成这项任务有什么特别的原因吗?是的,因为我是学生,练习中的问题是这样做。也许你应该添加一些缩进,让你的代码更容易阅读?