Achive交错多线程执行

时间:2015-05-01 20:48:36

标签: c multithreading scheduling

我有两个方法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

的随机顺序

0 个答案:

没有答案