/ Published in: C
These are the basic commands to use Mutex Threads in C
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
#include <pthread.h> //this is our lock and we use it to lock and unlock our mutex when shared data is accessed. pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER //the signature of the thread function always looks like this. void* thread_function(void* arg) { //before accessing the shared resource pthread_mutex_lock(&lock); //do something access your shared resource pthread_mutex_unlock(&lock); pthread_exit(NULL); } //creating and calling threads int main() { pthread_t threads[3]; pthread_create(threads[0], NULL, &thread_function, void *arg); pthread_create(threads[1], NULL, &thread_function, void *arg); pthread_create(threads[2], NULL, &thread_function, void *arg); //join the threads, join call waits for all threads to finish int i; for(i = 0; i < 3; i++) { pthread_join(threads[i], NULL); } //after you are finish you should always destroy the thread pthread_mutex_destory(&lock); }