C++ With Pthreads: Ryan M. Swanstrom December 27, 2008
C++ With Pthreads: Ryan M. Swanstrom December 27, 2008
Ryan M. Swanstrom
December 27, 2008
Abstract
This paper will demonstrate the use of Pthreads in C++. It is set up as lab exercise.
Contents
1 Creating and Joining Threads 2
1.1 Directions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2 Mutex Variables 3
2.1 Directions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3 Condition Variables 5
3.1 Simple Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.1.1 C++ Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.1.2 Directions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.2 Complex Thread Coordination Example . . . . . . . . . . . . . . . . . . . . 6
3.2.1 C++ Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.2.2 Directions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
A Setup Netbeans 8
1 Creating and Joining Threads
#include
#include
#include
using namespace std;
1.1 Directions
1. Compile and run the supplied code.
5. Does “thread a(): after work” get printed out? Why/Why not?
2 Mutex Variables
#include
#include
#include
#include
using namespace std;
vector shared_vec;
int MAX_SIZE = 1;
//pthread_mutex_t mutex; // declare a mutex
void *thread_a(void* param); // thread function
void *thread_b(void* param); // thread function
// pthread_mutex_destroy(&mutex);
return (EXIT_SUCCESS);
}
2.1 Directions
1. Run the above code
5. Uncomment the mutex global variable and the mutex code in the main() method and
in thread a(). Leave the mutex commented out in thread b();
6. Run the program again.
13. Move the mutex lock and mutex unlock inside the for loop in both thread methods.
3 Condition Variables
3.1 Simple Example
3.1.1 C++ Code
#include <iostream>
#include <pthread.h>
using namespace std;
return (EXIT_SUCCESS);
}
3.1.2 Directions
1. Run the code numerous times.
2. Is the output always the same?
#include <stdlib.h>
#include <iostream>
#include <pthread.h>
using namespace std;
return (EXIT_SUCCESS);
}
3.2.2 Directions
1. Run the following code numerous times.
3. Try moving the pthread cond wait statement from thread b to after the mutex unlock.
A Setup Netbeans
1. Create a new project