C 使用互斥锁序列化POSIX线程

C 使用互斥锁序列化POSIX线程,c,multithreading,synchronization,posix,C,Multithreading,Synchronization,Posix,我试图制作一个程序,创建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 我如何才能做到这一点?这是一个解

我试图制作一个程序,创建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
我如何才能做到这一点?

这是一个解决方案:

#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;
}

如果你需要的行为是明确的序列,为什么你要使用多个线程?我知道我实际上不需要线程,但这是一个练习作业mutexes@MRezk:这不是互斥锁的真正用途。互斥锁用于保护对共享内存的访问。你想要的是执行一个特定的全局排序。瞧,你只回答了一半。我知道。这个问题的目的是练习,所以我尽量不破坏它:)这并不能保证OP要求的顺序。然后,OP看起来很混乱,所以不清楚正确的答案是什么。
gcc -D_REENTRANT -lpthread main.c