PDA

View Full Version : سوال در مورد یک برنامه multithreading



clapton
یک شنبه 19 آذر 1391, 02:11 صبح
سلام دوستان.من در درک این برنامه مشکل دارم.اینو استادم داده برای شروع کار در مورد multithreading.وقت اجراش میکنم با این دستور mutex به مشکل بر میخورم.دقیقا نمیفهم داره چیکار میکنه؟ میفهمم که داره لاک میکنه یه متغیری رو اما نمیدونم چه ترتیبی برای لاک کردن وجود داره .اگه براتون امکانش هست ممنون میشم برام توضیح بدید.
سپاس فراوان
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;

void *functionC1()
{
pthread_mutex_lock( &mutex1 );
printf("C1 dort 5 secondes\n");
sleep(5);
counter++;
printf("Counter value: %d\n",counter);
pthread_mutex_unlock( &mutex1 );
}
void *functionC2()
{
pthread_mutex_lock( &mutex1 );
counter++;
printf("C2 dort 10 secondes\n");
sleep(10);
printf("Counter value: %d\n",counter);
pthread_mutex_unlock( &mutex1 );
}


main()
{
int rc1, rc2;
pthread_t thread1, thread2;

/* Create independent threads each of which will execute functionC */

if( (rc1=pthread_create( &thread1, NULL, &functionC1, NULL)) )
{
printf("Thread creation failed: %d\n", rc1);
}

if( (rc2=pthread_create( &thread2, NULL, &functionC2, NULL)) )
{
printf("Thread creation failed: %d\n", rc2);
}

/* Wait till threads are complete before main continues. Unless we */
/* wait we run the risk of executing an exit which will terminate */
/* the process and all threads before the threads have completed. */

pthread_join( thread1, NULL);
pthread_join( thread2, NULL);

exit(0);
}