23,118
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t tstmutex;
void ThreadFnc(int *threadno);
int main(void)
{
int num1;
int num2;
pthread_t thread1;
pthread_t thread2;
pthread_mutexattr_t attr;
int type;
pthread_mutexattr_init(&attr);
if (pthread_mutex_init(&tstmutex, &attr) < 0)
{
printf("pthread_mutex_init failed.\n");
return -1;
}
num1 = 1;
if (pthread_create(&thread1, NULL, (void *)ThreadFnc, (void *)&num1) < 0)
{
printf("pthread_create thread1 failed.\n");
}
usleep(5000);
num2 = 2;
if (pthread_create(&thread2, NULL, (void *)ThreadFnc, (void *)&num2) < 0)
{
printf("pthread_create thread2 failed.\n");
}
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_mutex_destroy(&tstmutex);
return 0;
}
void ThreadFnc(int *threadno)
{
int i=0;
if (*threadno == 1)
{
for(i=0; i< 5; i++)
{
printf("thread %d try to lock mutex. \n", *threadno);
if (pthread_mutex_lock(&tstmutex) < 0)
{
printf("pthread_mutex_lock failed.\n", *threadno);
}
printf("pthread_mutex_locked by thread %d.\n");
sleep(1);
printf("thread %d try to lock mutex.\n", *threadno);
if (pthread_mutex_unlock(&tstmutex) < 0)
{
printf("pthread_mutex_unlock failed.\n");
}
printf("pthread_mutex_unlocked by thread %d.\n", *threadno);
}
}
else
{
printf("thread %d try to lock mutex. \n", *threadno);
if (pthread_mutex_lock(&tstmutex) < 0)
{
printf("pthread_mutex_lock failed.\n", *threadno);
}
printf("pthread_mutex_locked by thread %d.\n");
sleep(1);
printf("thread %d try to lock mutex.\n", *threadno);
if (pthread_mutex_unlock(&tstmutex) < 0)
{
printf("pthread_mutex_unlock failed.\n");
}
printf("pthread_mutex_unlocked by thread %d.\n", *threadno);
}
}