Reputation: 546
I have two methods, fun1
and fun2
, which are called by two different set of threads. 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
Upvotes: 0
Views: 263
Reputation: 121397
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.
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. You can altogethter remove the two loops involving pthread_join calls and simply call pthread_exit(NULL);
instead, after creating all the threads which will allow all threads to continue while only main thread will exit.
Upvotes: 2