我正在尝试创建一个程序,创建3个线程threa1 thread2和thread3 thread1打印thread1 5次,thread2打印thread2 5次,thread3打印thread3 5次 我想使用互斥锁来获得此输出
thread1
thread1
thread1
thread1
thread1
thread2
thread2
thread2
thread2
thread2
thread3
thread3
thread3
thread3
thread3
我该怎么做?
答案 0 :(得分:0)
这是一个解决方案:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include <pthread.h>
#define MAX_PRINT 5
#define MAX_THREAD 3
static pthread_mutex_t mThread[MAX_THREAD] = {PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER};
void * start_thread(void * arg)
{
int thNb = *((int*)arg);
int i = 0;
pthread_mutex_lock(&mThread[thNb]);
for (i = 0; i < MAX_PRINT; i++) {
fprintf(stdout, "thread%d\n", thNb);
}
pthread_mutex_unlock(&mThread[thNb]);
return NULL;
}
int main()
{
pthread_t thread[MAX_THREAD];
int arg[MAX_THREAD];
int i = 0;
printf("Init Mutex for all threads ...");
for (i = 0; i < MAX_THREAD; i++) {
pthread_mutex_lock(&mThread[i]);
}
printf("OK\n");
printf("Creating threads ...");
for (i = 0; i < MAX_THREAD; i++) {
arg[i] = i;
pthread_create(&thread[i], NULL, &start_thread, &arg[i]);
}
printf("OK\n");
printf("::::::::::::::::: OUTPUT THAT YOU WANT :::::::::::::::::::::: \n");
for (i = 0; i < MAX_THREAD; i++)
{
pthread_mutex_unlock(&mThread[i]);
pthread_join(thread[i], NULL);
}
return 0;
}
使用以下方式编译:
gcc -D_REENTRANT -lpthread main.c