简体   繁体   English

主动交织多线程执行

[英]Achive interleaving multi-thread execution

I have two methods, fun1 and fun2 , which are called by two different set of threads. 我有两个方法fun1fun2 ,它们由两组不同的线程调用。 I want to interleave their execution in a random order, the same way the order is random inside each of the two set of threads. 我想以随机顺序交错执行,就像在两组线程中每个线程内部的顺序是随机的一样。 How can I achieve this? 我该如何实现?

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

}

Output : 输出

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

Desired output : 所需输出

Random order of both function 1 and function 2 function 1function 2随机顺序

By this I want to interleave their execution in a random order if you mean fun1 and fun2 to be executed in no fixed order then remove the loop with pthread_join() calls after the creating first group of threads (which waits for the first group to finish execution) and put it after creating all threads. 这样,如果您要表示fun1fun2以不固定的顺序执行,那么我想以随机顺序交错执行它们,然后在创建第一组线程之后等待pthread_join()调用删除循环(等待第一组线程完成)执行),并在创建所有线程后将其放入。

By the way if you simply want the threads to finish the execution on their own and there's no need for main thread to check status , then there's no need for pthread_join() calls at all. 顺便说一下,如果您只是希望线程自己完成执行,并且不需要主线程检查状态,那么根本就不需要pthread_join()调用。 You can altogethter remove the two loops involving pthread_join calls and simply call pthread_exit(NULL); 您可以完全删除涉及pthread_join调用的两个循环,而只需调用pthread_exit(NULL); instead, after creating all the threads which will allow all threads to continue while only main thread will exit. 相反,在创建所有线程之后,这将允许所有线程继续运行,而仅主线程将退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM