Here is a simple program using pthreads and controlling access to a common global array (string).
Without the mutex, the threads would alter the string at the same time and create undesired results.
#include #include #include pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // create a global initializer char GlobalString[] = "Hello World"; void* ThreadFunc (void *num) { int j; int i= *(int*)num; // function accepts a pointer to any type // but we need to cast it to an int for (j = 1; j #include #include //A bad idea //void *thread(void *vargp) { // printf("First Thread No' %ld\n",pthread_self()); // int *ptr = (int*)vargp; //int i= *ptr; //printf("in the thread %d\n",i ); //pthread_exit((void*)ptr); // } void *thread(void *vargp) { printf("First Thread No' %ld\n",pthread_self()); // int *ptr = (int*)vargp; // int i= *ptr; //printf("in the thread %d\n",i ); pthread_exit((void*)vargp); } void *thread2(void *vargp) { printf("Second Thread No' %ld\n",pthread_self()); vargp = (int*) malloc(sizeof(int)); *((int*)vargp) = 31; //printf("in the second thread %d\n",*((int*)vargp) ); pthread_exit(vargp); } int main() { int i = 42; int * m; int * n = &i; pthread_t tid, tid2; pthread_create(&tid, NULL, thread, n); pthread_create(&tid2, NULL, thread2, m); pthread_join(tid, (void**)&n); pthread_join(tid2, (void**)&m); printf("tid = %d\n",*n); printf("tid2 = %d\n",*m); } Also bad #include #include void *thread(void *vargp) { printf("First Thread No' %ld\n",pthread_self()); int *ptr = (int*)vargp; pthread_exit((void*)*ptr); } void *thread2(void *vargp) { printf("Second Thread No' %ld\n",pthread_self()); int *ptr = (int*)vargp; *ptr = 0; pthread_exit((void*)31); } int main() { int j,i = 42; pthread_t tid, tid2; pthread_create(&tid, NULL, thread, (void*)&i); pthread_create(&tid2, NULL, thread2, (void*)&i); pthread_join(tid, (void**)&i); pthread_join(tid2, (void**)&j); printf("tid = %d\n",i); printf("tid2 = %d\n",j);}