C语言之简单使用pthread构建线程并运行

当前版本:eclipse c++MinGW-W64-builds-4.3.5widnwos

1. 声明

当前内容主要为使用C语言库pthread记录创建和使用线程的demo

2. 基本demo

#include <stdio.h>
#include <stdlib.h>
// 从unistd中导入sleep函数
#include<unistd.h>
// 导入需要使用的线程库
#include <pthread.h>
/**
 * 	@description 当前内容主要为测试和使用线程,
 * 	@author hy
 * 	@createTime 2022-04-16
 */

void startThread(void *(*run)(void *), void *arg);
int shutdownNum = 1;
int modifyNum = 0; // 一个全局的共享变量
int defaultSleepTime = 200;
// 这里表示一个线程
void* run(void* arg) {
	// 得到当前执行的线程的执行id
	pthread_t th = pthread_self();
	printf("current execute thread id is %I64d\n",th);
	char* thread_name = NULL;
	// 校验参数数量和参数个数
	if (!arg || arg <= 0) {
		printf("exit with error!\n");
		shutdownNum--;
		// 将参数的值进行赋值操作
		pthread_exit("arg len <= 0");
	} else {
		thread_name = ((char**) arg)[0];
	}
	printf("start to printf info\n");
	fflush(stdout);
	printf("thread name ==> %s\n", thread_name);
	fflush(stdout);
	int num = 0;
	// 执行5次打印就结束
	while (num < 5) {
		modifyNum++;
		printf("print %s : %d\n", thread_name, ++num);
		printf("print %s : modifyNum : %d\n", thread_name, modifyNum);
		fflush(stdout);
		// 表示使用打印为1秒每次sleep(1);
		_sleep(defaultSleepTime);//表示休眠200毫秒
	}
	printf("%s exit!\n",thread_name);
	fflush(stdout);
	shutdownNum--;
	pthread_exit("num >5");
	return NULL;
}

int main(int argc, char **argv) {
	void *(*func)(void *) = run;
	char* arg[2] = { "thread-1" };
	void* args = arg; // 使用携带正确参数的可以执行,否则认为不可执行
	printf("before create thread\n");
	startThread(func, args);
	printf("after create thread\n");
	while (shutdownNum > 0) {
		printf("main thread wait! shutdownNum = %d\n",shutdownNum);
		fflush(stdout);
		sleep(1);
	}
	printf("main thread shutdown!\n");
	printf("modifyNum = %d",modifyNum);
	return 0;
}
// 表现为启动一个线程,给定一个函数和参数
void startThread(void *(*run)(void *), void *arg) {
	pthread_t th;
	const pthread_attr_t *attr = NULL;
	void *(*func)(void *) = run;
	int result = pthread_create(&th, attr, func, arg);
	if (result != 0) {
		// 表示无法创建该线程
		printf("can't create thread in current application!");
		exit(-1);
	}

	// 表现为join操作,即线程必定阻塞主线程执行,&res表示将返回结果拿到
	//pthread_join(th, res);
}

这里主要为使用pthread_create创建一个线程,线程创建会自己启动(如果主线程没有退出),pthread_join表示直接阻塞主线程,pthread_exit表示让线程退出不再执行任务

输出结果:
在这里插入图片描述

3. 在编写和执行期间遇到的问题

在windows环境中并使用eclispse c++进行c的多线程代码执行中遇到的问题

  1. printf没有作用,eclipse不会在控制台打印输出,结果通过百度发现eclispe会将printf的数据放入缓冲区,所以需要调用fflush(stdout)才会生效
  2. 执行时发现如果main线程不进行等待,那么多线程程序一般不会被执行,所以程序代码中有让main线程等待的代码(可以使用pthread_join来阻塞main线程)
  3. 对于多个线程环境有并发问题(可以使用互斥锁解决)
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值