Multithreading 如何使用互斥
我应该把锁和解锁互斥锁放在哪里,以便线程交替打印?谢谢:D 实现一个创建两个线程的程序。线程将打印其ID(pthread_self)10次,然后停止。确保打印的ID始终交替(即A、B、A、B等)Multithreading 如何使用互斥,multithreading,pthreads,mutex,Multithreading,Pthreads,Mutex,我应该把锁和解锁互斥锁放在哪里,以便线程交替打印?谢谢:D 实现一个创建两个线程的程序。线程将打印其ID(pthread_self)10次,然后停止。确保打印的ID始终交替(即A、B、A、B等) #包括 #包括 #定义n2 pthread_mutex_t mtx; void*func(void*arg){ int i=0; int f=1; 对于(i=0;i如果您想要可预测的有序输出A、B、A、B、A、B,最适合使用的工具是单线程控制 为了浪费两个线程的时间,您可以定义一个名为“turn”的共享
#包括
#包括
#定义n2
pthread_mutex_t mtx;
void*func(void*arg){
int i=0;
int f=1;
对于(i=0;i如果您想要可预测的有序输出A、B、A、B、A、B,最适合使用的工具是单线程控制
为了浪费两个线程的时间,您可以定义一个名为“turn”的共享变量,该变量指示打印内容的轮到谁。每个线程等待一个条件变量,直到“turn”变量等于自身。然后它执行顺序任务,设置“turn”变量传递给另一个线程并发出条件信号。好的,最好的答案是“不要尝试-使用一对信号量传递一个“打印令牌”。
#include <stdio.h>
#include <pthread.h>
#define N 2
pthread_mutex_t mtx;
void* func (void* arg) {
int i=0;
int f=1;
for(i=0; i<10; i++) {
printf("%d%s%d\n",f ,": ", (int)pthread_self());
f++;
}
return NULL;
}
int main() {
int i;
pthread_t thr[N];
pthread_mutex_init(&mtx, NULL);
for(i=0; i<N; i++) {
pthread_create(&thr[i], NULL, func, NULL);
}
for(i=0; i<N; i++) {
pthread_join(thr[i], NULL);
}
pthread_mutex_destroy(&mtx);
return 0;
}