简体   繁体   中英

Creating and managing threads with pthreads()

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 ababababa . And suppose thread1 is printing a and thread2 is printing b . This means that thread1 executes then hands over the control to thread2 . Then thread2 prints b and control is handed over back to thread1 , 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?

eg: 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;
}

Have a global variable sum and in Thread1 add 10 to sum 1000 times and in Thread2 subtract 5 from sum 1000 times. Run both the Threads and see the output. Race condition will occur. Peterson's algorithm is to avoid race condition. Here sum += 10 and sum -= 5 are the critical sections. Now implement Peterson's algorithm and see the output.

This is the best example to demonstrate the working of Peterson's algorithm.

Ok. So i found out that both my assumptions were wrong. Cause I assumed that threads that are created will be executed serially. But when creating threads, the OS will execut the threads randomly and in parallel. so I implemented it as below:

create_thread1(call function1)
create_thread2(call function2)

function1(){
  loop
}

function1(){
  loop
}

A partial answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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