POSIX Threads and Joins – Parallel Programming – PART 1

During a long time we were “blessed” with computers that had only single CPU. The single CPU usually had a mediocre single core and thread. All software developed on that time executed sequential processing.

However, multi-cores and multi-threads processors were introduced in the market but if you do not develop your software trying to explore the hardware advantages your software might have the same performance if running in a single cpu machine.

You need to think also if you software will run in a computer isolated or if your software will be able to run in multiple computers sharing a common network and organize different tasks to resolve a common problem.

Today, I will write this post for my own reference using the POSIX threads and how to have the best usage of joins and mutex implementation. I am running in a ubuntu 10.04 but if you are running Windows you can use these examples installing the POSIX win32 compatibility module or installing Cygwin to simulate a linux shell.

Code compilation

All codes on this post were compiled using gcc and invoking the POSIX libraries thru command like under ubuntu 10.04. For example you can use:

gcc -pthread <my source code.c>

Threads

The first code is related to a model where we do not share the same memory space and there is no policy regarding the thread priorities or resources access management (although the threads runs in the same process sharing the same memory space this first example to resource are conflicted).

It is a simple code that creates 3 threads, passes arguments to them using strings and integers and then they are terminated.

Take a look in the code below:

</pre>
void *print_message_function( void *ptr );
void *print_integer_function( void * i );
main()
{
 pthread_t thread1, thread2, thread3;
 char *s_parameter_t1 = "thread 1 - passing a string!";
 char *s_parameter_t2 = "thread 2 - passing a string!";
 int i_parameter_t3 = 1973; /* my birthday */
 int i_result_t1, i_result_t2, i_result_t3;

/* Creating two threads.. one using a funtion to process a string and another one to a integer
 - Note for multiple data you can use a data structure as parameter making a cast to void *
 - the data passed is shared in memory space for ALL threads of same process, so passing pointer
 addresses could be dangeours in concurrence state */
 i_result_t1 = pthread_create( &thread1, NULL, print_message_function, (void*) s_parameter_t1);
 i_result_t2 = pthread_create( &thread2, NULL, print_message_function, (void*) s_parameter_t2);
 i_result_t3 = pthread_create( &thread3, NULL, print_integer_function, (void*) &i_parameter_t3);

printf("execute me several times.. you will see no order and possile concurrences !!!\n");

/* checking if there is some thread fail */
 if (i_result_t1 == i_result_t2 == i_result_t3 != 0)
 {
 printf("Thread 1 returns: %d\n",i_result_t1);
 printf("Thread 2 returns: %d\n",i_result_t2);
 printf("Thread 3 returns: %d\n",i_result_t3);
 }

/* termination of threads.. we could kill all thread using exit(0) to aborting the process*/
 pthread_exit(&thread1);
 pthread_exit(&thread2);
 pthread_exit(&thread3);
}

void *print_message_function( void *ptr )
{
 char *message;
 message = (char *) ptr;
 printf("%s \n", message);
}

void *print_integer_function(void * i)
{
 int i_value = *((int *)i);
 printf("value integer %d\n",i_value);
}
<pre>

Basically we are creating three threads using pthread_create(), where 2 received a string parameter and one a integer parameter. Then the threads are terminated using pthread_exit(), thus the “thread pointers” are free at this time.

Compile and run the code several times.. you will see something like this in your shell:

bytesthink@ubuntu:~/code/code$ gcc -pthread pthreads.c
bytesthink@ubuntu:~/code/code$ ./a.out
execute me several times.. you will see no order and possile concurrences !!!
thread 2 – passing a string!
thread 1 – passing a string!
value integer 1973
bytesthink@ubuntu:~/code/code$ ./a.out
thread 1 – passing a string!
execute me several times.. you will see no order and possile concurrences !!!
value integer 1973
thread 2 – passing a string!
bytesthink@ubuntu:~/code/code$ ./a.out
thread 1 – passing a string!
thread 2 – passing a string!
execute me several times.. you will see no order and possile concurrences !!!
value integer 1973


Note there is no policy used to execute the entry points functions. You can see the code is not sequential because the threads 1, 2 and 3 are executed and no order is respected. The machine executes the first thread available in parallel manner.

Synchronizing threads with JOIN

The previous example is a good model when we have threads solving different problems (tasks) and there is no independence among them because the “main” does not care about the order of results processed by each one. Let’s change the code a little bit in order to allow us to synchronize the threads in the “main” code. For this, let’s use pthread_join() function:

</pre>
void *print_message_function( void *ptr );
void *print_integer_function( void * i );
main()
{
 pthread_t thread1, thread2, thread3;
 char *s_parameter_t1 = "thread 1 - passing a string!";
 char *s_parameter_t2 = "thread 2 - passing a string!";
 int i_parameter_t3 = 1973; /* my birthday */
 int i_result_t1, i_result_t2, i_result_t3;

/* Creating two threads.. one using a funtion to process a string and another one to a integer
 - Note for multiple data you can use a data structure as parameter making a cast to void *
 - the data passed is shared in memory space for ALL threads of same process, so passing pointer
 addresses could be dangeours in concurrence state */
 i_result_t1 = pthread_create( &thread1, NULL, print_message_function, (void*) s_parameter_t1);
 pthread_join(thread1, NULL);
 i_result_t2 = pthread_create( &thread2, NULL, print_message_function, (void*) s_parameter_t2);
 pthread_join(thread2, NULL);
 i_result_t3 = pthread_create( &thread3, NULL, print_integer_function, (void*) &i_parameter_t3);
 pthread_join(thread3, NULL);

printf("execute me several times.. you will see no order and possile concurrences !!!\n");

/* checking if there is some thread fail */
 if (i_result_t1 == i_result_t2 == i_result_t3 != 0)
 {
 printf("Thread 1 returns: %d\n",i_result_t1);
 printf("Thread 2 returns: %d\n",i_result_t2);
 printf("Thread 3 returns: %d\n",i_result_t3);
 }

/* termination of threads.. we could kill all thread using exit(0) to aborting the process*/
 pthread_exit(&thread1);
 pthread_exit(&thread2);
 pthread_exit(&thread3);
}

void *print_message_function( void *ptr )
{
 char *message;
 message = (char *) ptr;
 printf("%s \n", message);
}

void *print_integer_function(void * i)
{
 int i_value = *((int *)i);
 printf("value integer %d\n",i_value);
}
<pre>

Now execute the code several times again. You will see:

bytesthink@ubuntu:~/code/code$ gcc -pthread pthreads_join.c
bytesthink@ubuntu:~/code/code$ ./a.out
thread 1 – passing a string!
thread 2 – passing a string!
value integer 1973
execute me several times.. you will see no order and possile concurrences !!!
bytesthink@ubuntu:~/code/code$ ./a.out
thread 1 – passing a string!
thread 2 – passing a string!
value integer 1973
execute me several times.. you will see no order and possile concurrences !!!
bytesthink@ubuntu:~/code/code$ ./a.out
thread 1 – passing a string!
thread 2 – passing a string!
value integer 1973
execute me several times.. you will see no order and possile concurrences !!!
bytesthink@ubuntu:~/code/code$ ./a.out
thread 1 – passing a string!
thread 2 – passing a string!
value integer 1973
execute me several times.. you will see no order and possile concurrences !!!
bytesthink@ubuntu:~/code/code$ ./a.out
thread 1 – passing a string!
thread 2 – passing a string!
value integer 1973

As you see, the “join” has a function of blocking. It means, the pthread_join() making usage of the thread_id identified by the thread pointer, is saying to “main” execution, wait to finish this execution. So, even if thread 2 or 3 finish first, the main will remain blocked waiting the thread 1 finish its work because there is a “join” defined. So, on this way you can guarantee the sequence of final results but you still have the threads working in parallel.

Source Code

You can download the first code here!

What’s coming in next part ?

In the next part let’s take a look in mutexes and conditional mutexes. Let’s talk also how useful is volatile datatype in C/C++ for multi-core processors. No time to write more on this wonderful Sunday! Mexican food is waiting for me!!! 🙂

129 thoughts on “POSIX Threads and Joins – Parallel Programming – PART 1

  1. Interesting article introduction article but could you adapt your layout/css/code so that one could read your code without horizontal scrolling? The code block is only ~30 char wide on my screen.

  2. Pingback: jordan cp3.xi orange uk trainers

  3. Pingback: cat carter maize

  4. Pingback: bleu jaune rouge big boys lebron soldier 11

  5. Pingback: air force 1 low balsam green uk trainers

  6. Pingback: uk trainers preschool nike free run 2 boy flesh

  7. Pingback: marron kaki rouge supreme justin bieber t shirt

  8. Pingback: hvid lyser酶d nike zvezdochka

  9. Pingback: sort r酶d nike dunk sky hi essential

  10. Pingback: 胁芯谢褜褌 锌褍褉锌褍褉薪褘泄 adidas 2012 superstar animals

  11. Pingback: cheetah print jordan 1

  12. Pingback: uk trainers merrell proterra sport gtx where to get it

  13. Pingback: womens game dion lewis 33 tennessee titans jersey

  14. Pingback: wholesale kids brandon scherff 75 washington redskins jersey

  15. Pingback: adidas eqt support rf pk equipment primeknit pearl grey whit

  16. Pingback: nike free rn distance nike free rn distance womens

  17. Pingback: off shoulder maxi dress black panther ready sale

  18. Pingback: skechers boots for girls baby grey pink kids white quality

  19. Pingback: top quality mens new york giants era black 2017 sideline 9fifty snapback hat

  20. Pingback: tacvasen 40l military backpacks waterproof travel backpack army soldier knapsack mollebat backpacks

  21. Pingback: nike lunar control vapor 2

  22. Pingback: sitesbooster

  23. Pingback: sexy black zip through long sleeved bodysuit

  24. Pingback: puma baby shoes

  25. Pingback: black salomon womens running shoes s lab sense m nwt cross country ultra lightweight trail footwear

  26. Pingback: biconservancy

  27. Pingback: up to 5000 gift card on regular giuseppe zanotti shoes

  28. Pingback: saucony peregrine 4 negro verde citron

  29. Pingback: Balenciaga UK

  30. Pingback: nike explorer 2 s dark greylaser orangepure platinum golfsko f r m n

  31. Pingback: new nike authentic paris saint germain fly emirates drifit soccer jersey mens xl

  32. Pingback: womens derrick rose wearing d rose 6

  33. Pingback: lionel messi barcelona star has no life dani osvaldo

  34. Pingback: usb charging light flashing simulation sneakers cr

  35. Pingback: nike air max uptempo urban haze collection

  36. Pingback: chivas black jersey size small medi

  37. Pingback: the north face tailout hooded rain jacket wine

  38. Pingback: chelsea home jersey

  39. Pingback: air jordan retro 17 black wine outlet online v6v9rs1

  40. Pingback: nikeair force 1 07 lv8 urban hazesailteam orange

  41. Pingback: dog key ring labrador black by paper island top dog cat keyrings buy online in omankitchen amp home products in oman see prices

  42. Pingback: ray ban rb3044 aviator sunglasses arista frame crystal deep greeonly 1998 mod fashion

  43. Pingback: ladies 1920s teal flapper fancy dress costume fancy me lim

  44. Pingback: red north face jacket womens twitter.com

  45. Pingback: nike all black basketball shoes mens lebron 13 for

  46. Pingback: adidas marathon 84 pas cher

  47. Pingback: glistening air jordan game royal mens biggest auction nike jordan spike forty pe

  48. Pingback: frame sunglasses black sunglasses

  49. Pingback: find spring summer 2018 men ted baker greyene derby brogue shoes black lining 100

  50. Pingback: military style backpack

  51. Pingback: carter s baby toddler boy s

  52. Pingback: harley davidson ladies low cut sneakers

  53. Pingback: michael weston sunglasses brand

  54. Pingback: womens flyknit running shoes puresegway

  55. Pingback: summer air jordan reveal prem mens casuals wolf grey orange 834229 015

  56. Pingback: miami heat mitchell ness nba hyper colors snapback cap

  57. Pingback: sam edelman gladiator off white leather women shoes

  58. Pingback: lacey yellow economy bart simpson curly spiky costume

  59. Pingback: exclusive nike sb shoes

  60. Pingback: lebron 15 hollywood rust pink short match

  61. Pingback: econ贸mica nike free run 5 0 v5 hombres zapatos negro plata ebay ehb9070

  62. Pingback: discount cheap nike shox avenue leather mens running shoes

  63. Pingback: take a look at the slick looking nike air max vac tech pack

  64. Pingback: the north face osito 2 jacket womens previous season

  65. Pingback: puma fierce strap training white women麓s shoes

  66. Pingback: womens beats 3 studio

  67. Pingback: y3 yohji yamamoto sandals men spring summer 2018

  68. Pingback: nike air jordan mens retro 13 xiii history of flight 414571 103 mens jordan size

  69. Pingback: us mens soccer store jersey

  70. Pingback: nike white blue men 07 air force 1 mid shoes

  71. Pingback: nike air max 95 ankle support

  72. Pingback: asics gel kayano evoasics gel kayano trainer

  73. Pingback: image is loading under armour storm womens fleeced lined soft running

  74. Pingback: nike woodside british tan brown acg boots

  75. Pingback: adidas nemeziz 17.4 fg at 8970727

  76. Pingback: vera bradley kensington limited edition ladies tortoise shell link watch nib

  77. Pingback: 1800 hotline bling 1 800

  78. Pingback: nike air max 03

  79. Pingback: unisex slouch beanie hat knitted long women men cap suitable for all head sizes in skullies beanies from apparel accessories on alibaba

  80. Pingback: ss608ladies fashion korean style hoodies fashion tops loose long sleeved sweate

  81. Pingback: vans classic logo jumper

  82. Pingback: huarache nike damen schwarz wei脽

  83. Pingback: christian louboutin henri mens flat suede sneakers black uk sale

  84. Pingback: shop adidas mens neo cloudfoam racer tr running shoe core black

  85. Pingback: nike shox turbo 13 mens tennis shoes charcoal black

  86. Pingback: vans hats milford beanie hat heather grey from village hats

  87. Pingback: kids sandals ebay

  88. Pingback: neighborhood and adidas originals to release four shoe collaboration in february

  89. Pingback: nike hypervenom phantom iii df sg pro ac 899982 306 size 11

  90. Pingback: dope air jordan dave white tees giveaway

  91. Pingback: customize them with your team motto mascot player names and so much morechoose a t shirt to get started and customize online with a few clicks

  92. Pingback: buy cheap air jordan 6 vi black cat 16 for sale online

  93. Pingback: ladies 415 clothing inc

  94. Pingback: deal of the day quot 15.6 inch laptop bag anti theft backpack with usb charging school

  95. Pingback: vinterjakke til herre fra helly hansen parka str. l

  96. Pingback: offre femme cuir

  97. Pingback: 2018 ah7006 201 nike air vapormax flyknit 2 grey pink

  98. Pingback: points de vente 脿 vendre vert sandales femme 脿 petit talon 茅pais de 3

  99. Pingback: womens leopard backpack girls leopard travel female laptop backpacks school bag

  100. Pingback: kids winter beanie women pom pom knitted beanie hat warm thicker skullies hats fashion skull caps skull cap beanie boo from newnewnew 2.42

  101. Pingback: cleats low top outdoor football boots soccer shoes x 16.1 fg ag cheap messi cleats soccer boots new 17 kids original soccer us 39 45

  102. Pingback: adidas nmd hu trail world blank canvas ac7031 sneaker bar detroit

  103. Pingback: nike zoom kobe xi 11 elite low 4kb

  104. Pingback: czarne obuwie sportowe z po艂yskiem jennifer w sk epie deezee p

  105. Pingback: 褍褋谢褍谐懈 邪胁褌芯褉械胁懈蟹芯褉褉芯

  106. Pingback: daisy cecil on in 18 discount nikes shoes sneakers jordans

  107. Pingback: sukienka ipsy ondon nowa 4 5 at ceny i opinie ceneo p

  108. Pingback: nike store bourbon shopping pompeia veja s茫o pau o

  109. Pingback: k酶b master ice skibukser til b酶rn i sort sportmaster

  110. Pingback: karen by simonsen omage jakke gr酶n gratis fragt

  111. Pingback: adidas superstar j 154 rozmiar 36 2 3

  112. Pingback: promo莽茫o t锚nis puma. novo. tamanho 39 roupas e ca 莽ados barroca

  113. Pingback: t锚nis lacoste showcourt urs branco compre agora kanui brasil

  114. Pingback: vendita clearance scarpe uomo redskins toniko sneakers basse noir basso prezzo negozio on line

  115. Pingback: acquista nike air max 2018 donna off35 sconti

  116. Pingback: leinen und seide stoffe wie gemacht f眉r den sommer hawes

  117. Pingback: r贸偶owe cz贸艂enka szpi ki wojas

  118. Pingback: mxd katzen beutel hundetasche haustier rucksack haustier heraus tragetasche haustier rucksack

  119. Pingback: haslev jens e sport i jernbanegade skilter med oph酶rsudsalg

  120. Pingback: t锚nis reebok crossfit speed field cinza branco

  121. Pingback: caroll pull kl茅ber v锚tements pulls et gilets femme bleu marine

  122. Pingback: add to wishlist super restorative daily experts set. exclusive. clarins

  123. Pingback: fred mazzola jaeger lecoultre catalogue

  124. Pingback: pijushi designer handbags for women floral purses top handle satchel handbags 22328 blue

  125. Pingback: home soft hood bonnet attachment haircare salon hair dryer price

  126. Pingback: one for the panerai heads page 2

  127. Pingback: ternos sem marcas de uso roupas e cal莽ados nossa senhora do

  128. Pingback: should i buy a louis vuitton up to 60 off

Leave a Reply