SHARE
TWEET

threadtest.c

jesusdiazvicoincibe Mar 3rd, 2015 (edited) 396 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * File: threadtest.c
  3.  * Author: Jesus Diaz Vico @ INCIBE (Spanish National Cybersecurity Institute).
  4.  * Date: March 3rd, 2015.
  5.  * Description: Example of source code with race conditions.
  6.  *
  7.  * Compile with:
  8.  *    gcc -g -lpthread -o threadtest threadtest.c
  9.  * and then use:
  10.  *    valgrind --tool=helgrind ./threadtest
  11.  *
  12.  * For studying the solution, uncomment lines  23, 30, 34, 46, 50, 63 and 77
  13.  * and repeat the process.
  14.  */
  15.  
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <pthread.h>
  19. #include <assert.h>
  20. #include <time.h>
  21.  
  22. int balance;
  23. /* pthread_mutex_t lock; */
  24.  
  25. static void* thread_credit(void *arg) {
  26.  
  27.         int i, final;
  28.  
  29.         for (i=0; i<100; i++) {
  30.                 /* pthread_mutex_lock(&lock); */
  31.                 final = balance + 100;
  32.                 usleep(rand() % 100);
  33.                 balance = final;
  34.                 /* pthread_mutex_unlock(&lock); */
  35.         }
  36.  
  37.         return;
  38.  
  39. }
  40.  
  41. static void* thread_debit(void *arg) {
  42.  
  43.         int i, final;
  44.  
  45.         for (i=0; i<100; i++) {
  46.                 /* pthread_mutex_lock(&lock); */
  47.                 final = balance - 100;
  48.                 usleep(rand() % 100);
  49.                 balance = final;
  50.                 /* pthread_mutex_unlock(&lock); */
  51.         }
  52.  
  53.         return;
  54.  
  55. }
  56.  
  57. int main () {
  58.  
  59.         pthread_t t1, t2;
  60.  
  61.         srand(time(NULL));
  62.  
  63.         /* assert(!pthread_mutex_init(&lock, NULL)); */
  64.  
  65.         /* Create thread #1 */
  66.         assert (!pthread_create(&t1, NULL, thread_credit, NULL));
  67.  
  68.         /* Create thread #2 */
  69.         assert (!pthread_create(&t2, NULL, thread_debit, NULL));
  70.  
  71.         /* Wait for them to finish */
  72.         pthread_join(t1, NULL);
  73.         pthread_join(t2, NULL);
  74.  
  75.         fprintf(stdout, "Final balance: %d\n", balance);
  76.  
  77.         /* pthread_mutex_destroy(&lock); */
  78.  
  79.         return 0;
  80.  
  81. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top