I went thorough different pthread tutorials on the web. here, here and here among others. But there is a questions that is still left unanswered, and was wondering if anyone could clarify it.
Question:
- Suppose I want to print
a b a b a b a b a
. And supposethread1
is printinga
andthread2
is printingb
. This means thatthread1
executes then hands over the control tothread2
. Thenthread2
printsb
and control is handed over back tothread1
, so on and so forth. In such a scenario, is it possible to create two threads and call each one at a time inside a loop that executes a specific number of times(using thread ID or some builtin function?)? Or do i have to create two threads each time using a loop?
e.g: should i do something like:
create_thread1()
create_thread2()
for loop
call thread1()
call thread2
or should i do something like:
for loop
create_thread1() to do something
create_thread2() to do something
EDIT: I removed part of the details from questions, cause users thought that was the question.
EDIT: code
void *func(void *arg){
int i;
while(i<30){
printf("%s\n",(char *)arg);
i++;
}
return 0;
}
int main(int argc, char *argv[]){
pthread_t thread1, thread2;
int rt1, rt2;
rt1 = pthread_create(&thread1, NULL, &func, "a");
rt2 = pthread_create(&thread2, NULL, &func, "b");
sleep(1);
return;
}