如何使用互斥锁 [英] How to use mutex
问题描述
我应该在哪里放置互斥锁,以便线程可以交替打印?谢谢:D
执行一个创建两个线程的程序.线程将打印其ID(pthread_self)10次,然后停止.确保打印的ID始终交替(即A,B,A,B,...)
#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;
}
如果要获得可预测的有序输出A,B,A,B,A,B,则最适合使用的工具是单控制线程. /p>
要在两个线程上浪费时间,可以定义一个共享变量"turn",该变量指示要打印哪些内容.每个线程都在等待条件变量,直到"turn"变量等于其自身为止.然后执行顺序任务,将"turn"变量设置为另一个线程并发出条件信号.
Where should i put the lock and unlock mutex in order for the threads to print alternatively? Thanks:D
Implement a program that creates two threads. The threads will print their ID (pthread_self) 10 times and then stop. Insure that the printed IDs alternate always (ie A, B, A, B, ...)
#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;
}
If you want the predictably ordered output A, B, A, B, A, B, the most appropriate tool to use is a single thread of control.
To do it wastefully with two threads, you can define a shared variable called "turn" which indicates whose turn it is to print something. Each thread waits on a condition variable until the "turn" variable is equal to itself. Then it carries out the sequential task, sets the "turn" variable to another thread and signals the condition.
这篇关于如何使用互斥锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!