实现交错多线程执行

Achive interleaving multi-thread execution

我有两个方法,fun1fun2,它们由两组不同的线程调用。我想以随机顺序交错执行它们,就像两组线程中的每一个线程内的顺序都是随机的一样。我怎样才能做到这一点?

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>
#include <stdint.h>


void * function1(){

    printf("function 1\n");
    pthread_exit(NULL);

}

void * function2(){

    printf("function 2\n");
    pthread_exit(NULL);

}

int main(int argc, char ** argv){

    int i;
    int error;
    int status;
    int number_threads1 = 4;
    int number_threads2 = 3;

    pthread_t thread1[number_threads1];
    pthread_t thread2[number_threads2];

    for (i = 0; i < number_threads1; i++){
        error = pthread_create(&thread1[i], NULL, function1, NULL);

        if(error){return (-1);}
    }

    for(i = 0; i < number_threads1; i++) {

        error = pthread_join(thread1[i], (void **)&status);

        if(error){return (-1);}   
    }

    for (i = 0; i < number_threads2; i++){
        error = pthread_create(&thread2[i], NULL, function2, NULL);

        if(error){return (-1);}
    }

    for(i = 0; i < number_threads2; i++) {

        error = pthread_join(thread2[i], (void **)&status);

        if(error){return (-1);}   
    }

}

输出:

function 1
function 1
function 1
function 1
function 2
function 2
function 2

期望输出:

function 1function 2

的随机顺序

通过这个我想以随机顺序交错执行 如果你的意思是 fun1fun2 没有固定顺序执行然后删除pthread_join() 的循环在创建第一组线程之后调用(等待第一组完成执行)并在创建所有线程之后放置它。

顺便说一下,如果您只是希望线程自己完成执行,而主线程不需要检查状态,那么根本不需要 pthread_join() 调用。您可以完全删除涉及 pthread_join 调用的两个循环,而只需调用 pthread_exit(NULL); 即可,在创建所有线程之后,这将允许所有线程继续,而只有主线程将退出。