← cproj

pthread - pass and return values to thrads

a8c337c8b502e17cbaaf2801ed79b9aef86df54d · ovidiucs · Dec 5, 2019 09:07

+11 −4 · 1 file changed

  • graph/db/pthreads/pthread_example.c +11 −4
diff --git a/graph/db/pthreads/pthread_example.c b/graph/db/pthreads/pthread_example.c
index 2fa691e..660cd94 100644
--- a/graph/db/pthreads/pthread_example.c
+++ b/graph/db/pthreads/pthread_example.c
@@ -3,29 +3,36 @@
 #include <pthread.h>
 // https://youtu.be/uA8X5zNOGw8
 void *foo(void *arg){
-  while(1) {
-  fprintf(stdout,"My Turn\n");
+  int *iptr = (int *) arg;
+  for (int i = 0; i < 5; i++){
+  fprintf(stdout,"My Turn and %d %d\n", i, *iptr);
+  (*iptr)++;
+
   sleep(1);
+
   }
   return NULL;
 }
 
 void bar(){
-  while(1) {
+  for (int i = 0; i < 2; i++){
   fprintf(stdout,"Your Turn\n");
   sleep(1);
   }
 
 }
 int main (int argc, char** argv) {
+  int i = 5;
   //1. Create thread.
   pthread_t newthread;
 
   //2. args, pthread_t address, NUL
-  pthread_create(&newthread, NULL,foo, NULL);
+  pthread_create(&newthread, NULL,foo, &i);
 
 
 //  foo();
    bar();
+  pthread_join(newthread,NULL);
+  fprintf(stdout,"Thread's done %d\n",i);
    return 0;
 }