Note that there are some explanatory texts on larger screens.

plurals
  1. POThread and Forks
    primarykey
    data
    text
    <p>I am relatively new to threads and forks. So to understand them a bit better I have been writing simple programs. One of the little programs I have written two programs, one to print a counter on two processes, and another with two threads. What I noticed is that the fork prints the counters interlaced while the thread prints one thread's counter and then the others. So the thread is not so parallel, but behaves more serial Why is that? Am I doing something wrong? </p> <p>Also, what exactly does pthread_join do? Even when I don't do pthread_join the program runs similarly.</p> <p>Here is my code for the thread</p> <pre><code>void * thread1(void *a){ int i =0; for(i=0; i&lt;100; i++) printf("Thread 1 %d\n",i); } void * thread2(void *b){ int i =0; for(i=0; i&lt;100; i++) printf("Thread 2 %d\n", i); } int main() { pthread_t tid1,tid2; pthread_create(&amp;tid1,NULL,thread1, NULL); pthread_create(&amp;tid2,NULL,thread2, NULL); pthread_join(tid1,NULL); pthread_join(tid2,NULL); return 0; } </code></pre> <p>And here is my code for fork</p> <pre><code>int main(void) { pid_t childPID; childPID = fork(); if(childPID &gt;= 0) // fork was successful { if(childPID == 0) // child process { int i; for(i=0; i&lt;100;i++) printf("\n Child Process Counter : %d\n",i); } else //Parent process { int i; for(i=0; i&lt;100;i++) printf("\n Parent Process Counter : %d\n",i); } } else // fork failed { printf("\n Fork failed, quitting!!!!!!\n"); return 1; } return 0; } </code></pre> <p>EDIT: How can I make the threaded program behave more like the fork program? i.e. the counter prints interweave.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload