多线程
线程有四种状态:新生状态、可运行状态、被阻塞状态、死亡状态。
多线程的几种实现方法
- 继承 Thread 类
- 实现 Runnable 接口再 new Thread
#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;
}
浙公网安备 33010602011771号