Skip to content
Snippets Groups Projects
Commit 157fc91b authored by Bruce Cowan's avatar Bruce Cowan :airplane:
Browse files

Add pthread example

parent 9f99a2d7
No related branches found
No related tags found
No related merge requests found
......@@ -36,4 +36,5 @@ subdir('array')
subdir('hashtable')
subdir('list')
subdir('openmp')
subdir('pthread')
subdir('winter')
executable('thread-incr', 'thread-incr.c',
dependencies: thread_dep,
link_with: lib_utils,
include_directories: incdir)
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <utils.h>
typedef struct
{
pthread_t thread;
int id;
int loops;
} ThreadData;
static volatile int glob = 0;
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static void
err_exit (const char *func)
{
fprintf (stderr, "Error: %s\n", func);
}
static void *
thread_func (void *arg)
{
ThreadData *data = (ThreadData *) arg;
for (int j = 0; j < data->loops; j++)
{
if (pthread_mutex_lock (&mtx))
err_exit ("pthread_mutex_lock");
printf ("Thread #%d: glob = %d\n", data->id, glob);
int loc = glob;
loc++;
glob = loc;
if (pthread_mutex_unlock (&mtx))
err_exit ("pthread_mutex_unlock");
}
return NULL;
}
int
main (int argc, char **argv)
{
int *loops = get_ints (argc, argv, 1, "Number of loops");
ThreadData *t1 = malloc (sizeof (ThreadData));
t1->id = 1;
t1->loops = *loops;
if (pthread_create (&t1->thread, NULL, thread_func, t1))
err_exit ("pthread_create");
ThreadData *t2 = malloc (sizeof (ThreadData));
t2->id = 2;
t2->loops = *loops;
if (pthread_create (&t2->thread, NULL, thread_func, t2))
err_exit ("pthread_create");
if (pthread_join (t1->thread, NULL))
err_exit ("pthread_join");
if (pthread_join (t2->thread, NULL))
err_exit ("pthread_join");
printf ("End: glob = %d\n", glob);
free (t1);
free (t2);
return 0;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment