I'm relatively new to streams and forks. Therefore, to understand them a little better, I wrote simple programs. One of the small programs I wrote two programs: one for printing the counter on two processes, and the other with two threads. I noticed that the fork prints counters alternating when a stream prints one flow counter, and then the rest. So, the flow is not so parallel, but it behaves more serially. Why? Am I doing something wrong?
Also, what exactly does pthread_join do? Even when I do not execute pthread_join, the program works the same way.
Here is my code for the stream
void * thread1(void *a){ int i =0; for(i=0; i<100; i++) printf("Thread 1 %d\n",i); } void * thread2(void *b){ int i =0; for(i=0; i<100; i++) printf("Thread 2 %d\n", i); } int main() { pthread_t tid1,tid2; pthread_create(&tid1,NULL,thread1, NULL); pthread_create(&tid2,NULL,thread2, NULL); pthread_join(tid1,NULL); pthread_join(tid2,NULL); return 0; }
And here is my fork code
int main(void) { pid_t childPID; childPID = fork(); if(childPID >= 0) // fork was successful { if(childPID == 0) // child process { int i; for(i=0; i<100;i++) printf("\n Child Process Counter : %d\n",i); } else //Parent process { int i; for(i=0; i<100;i++) printf("\n Parent Process Counter : %d\n",i); } } else // fork failed { printf("\n Fork failed, quitting!!!!!!\n"); return 1; } return 0; }
EDIT: How can I make a threaded program behave like a fork program? that is, the counter prints an interlacing.
source share