#include <stdio.h>
#include <pthread.h>
#include <Windows.h>
static int g_num = 0;
static int g_c = 0;
pthread_mutex_t gMutex_num = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t gMutex_c = PTHREAD_MUTEX_INITIALIZER;
void* test(void *para)
{
int a;
for (int i = 0; i < 1; i++) {
pthread_mutex_lock(&gMutex_num);
printf("pid = %d, g_num = %d\n",para, g_num++);
a = g_num;
pthread_mutex_unlock(&gMutex_num);
pthread_mutex_lock(&gMutex_c);
printf("pid = %d, g_c + a = %d\n",para, g_c + a);
pthread_mutex_unlock(&gMutex_c);
}
}
void* test1(void *para)
{
int b;
for (int i = 0; i < 1; i++) {
pthread_mutex_lock(&gMutex_c);
printf("pid = %d, g_c = %d\n",para, g_c++);
b = g_c;
pthread_mutex_unlock(&gMutex_c);
pthread_mutex_lock(&gMutex_num);
printf("pid = %d, g_num + b = %d\n",para, g_num + b);
pthread_mutex_unlock(&gMutex_num);
}
}
int main()
{
pthread_t thread_a;
pthread_create(&thread_a, NULL, test, (void *)1);
pthread_t thread_b;
pthread_create(&thread_b, NULL, test, (void *)2);
// pthread_t thread_c;
// pthread_create(&thread_c, NULL, test1, (void *)3);
// pthread_t thread_d;
// pthread_create(&thread_d, NULL, test1, (void *)4);
//
pthread_join(thread_a, NULL);
pthread_join(thread_b, NULL);
// pthread_join(thread_c, NULL);
// pthread_join(thread_d, NULL);
printf("\ng_num = %d g_c = %d\n", g_num, g_c);
return 0;
}
标签:NULL,thread,num,mutex,pthread,gMutex,多线程
From: https://www.cnblogs.com/zhouhongyuan/p/17772933.html