0

Here is the code that I have so far:

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int value = 0;
void *runner(void *param);
int main(){
    int pid;
    pthread_t tid;
    pthread_attr_t attr;
    pid = fork();

    if (pid == 0) {
      pthread_attr_init(&attr);
      pthread_create(&tid,&attr,runner,NULL);
      pthread_join(tid,NULL);
      printf("A: value = %d\n", value);
    }

    else if (pid > 0) {
     wait(NULL);
     printf("B: value = %d\n", value);
    }
}

void *runner(void *param){
    value = 5;
    pthread_exit(0);
}

I have identified the child and parent processes but I am not sure how to make A and B print interleaved.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362
Shayra
  • 9
  • 3
  • If you want "ABABABAB.." you need synchronization between the threads so they wait on eachother after printing a single character. Otherwise each thread will print as much as it can while it has the CPU and any mix of output is possible. – Jesper Juhl Feb 14 '20 at 15:36
  • 2
    Notice that we have now (since C++11) [``](https://en.cppreference.com/w/cpp/header/thread) instead of `pthread_*`. – Jarod42 Feb 14 '20 at 15:37
  • 2
    Why are you using raw pthreads in C++? What's wrong with [std::thread](https://en.cppreference.com/w/cpp/thread/thread) and friends? – Jesper Juhl Feb 14 '20 at 15:38
  • @JesperJuhl @Jarod42 It is how my professor wants us to type our code. I've read that we can now use `` but he does not want that. – Shayra Feb 14 '20 at 15:43
  • 1
    @Shayra In my opinion, your professor is behind the times... – Jesper Juhl Feb 14 '20 at 15:48
  • Does this help https://stackoverflow.com/questions/23586682/how-to-use-printf-in-multiple-threads ? I'm assuming you are having the two threads printing over each other and producing garbled output. If you just want them intersperced ABAB then use a loop. Threads are contrary to that -- you're not supposed to control when each one does stuff. – Kenny Ostrom Feb 14 '20 at 15:52
  • @Shayra what is the desired output in your case ? – Landstalker Feb 14 '20 at 15:54
  • If you want the threads to wait for each other, that is certainly achievable, but you have not even attempted it in your code. You'll have to make an attempt before you post that question. – Kenny Ostrom Feb 14 '20 at 15:58
  • Why `fork` *and* start a single thread? That thread doesn't do anything, the main thread starts it and immediately waits for it to finish. If this is a thread synchronization question, the `fork` doesn't belong. If this is a process synchronization question, the extra thread doesn't belong. – François Andrieux Feb 14 '20 at 16:02

0 Answers0