多线程
线程有四种状态:新生状态、可运行状态、被阻塞状态、死亡状态。
多线程的几种实现方法
- 继承 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;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧