多线程

线程有四种状态:新生状态、可运行状态、被阻塞状态、死亡状态。

多线程的几种实现方法

  1. 继承 Thread 类
  2. 实现 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;
}
posted @   邹木木  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示