Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * File: threadtest.c
- * Author: Jesus Diaz Vico @ INCIBE (Spanish National Cybersecurity Institute).
- * Date: March 3rd, 2015.
- * Description: Example of source code with race conditions.
- *
- * Compile with:
- * gcc -g -lpthread -o threadtest threadtest.c
- * and then use:
- * valgrind --tool=helgrind ./threadtest
- *
- * For studying the solution, uncomment lines 23, 30, 34, 46, 50, 63 and 77
- * and repeat the process.
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <assert.h>
- #include <time.h>
- int balance;
- /* pthread_mutex_t lock; */
- static void* thread_credit(void *arg) {
- int i, final;
- for (i=0; i<100; i++) {
- /* pthread_mutex_lock(&lock); */
- final = balance + 100;
- usleep(rand() % 100);
- balance = final;
- /* pthread_mutex_unlock(&lock); */
- }
- return;
- }
- static void* thread_debit(void *arg) {
- int i, final;
- for (i=0; i<100; i++) {
- /* pthread_mutex_lock(&lock); */
- final = balance - 100;
- usleep(rand() % 100);
- balance = final;
- /* pthread_mutex_unlock(&lock); */
- }
- return;
- }
- int main () {
- pthread_t t1, t2;
- srand(time(NULL));
- /* assert(!pthread_mutex_init(&lock, NULL)); */
- /* Create thread #1 */
- assert (!pthread_create(&t1, NULL, thread_credit, NULL));
- /* Create thread #2 */
- assert (!pthread_create(&t2, NULL, thread_debit, NULL));
- /* Wait for them to finish */
- pthread_join(t1, NULL);
- pthread_join(t2, NULL);
- fprintf(stdout, "Final balance: %d\n", balance);
- /* pthread_mutex_destroy(&lock); */
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement