利用互斥锁实现多个线程写一个文件

本文详细描述了一个C++程序,展示了如何使用pthread库创建并管理线程,以及在无限循环中加入互斥锁和取消点,确保线程能正确响应取消请求。
摘要由CSDN通过智能技术生成

代码

#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>

FILE *fp;

//线程函数1
void *wrfunc1(void *arg);
//线程函数2
void *wrfunc2(void *arg);
//线程函数3
void *wrfunc3(void *arg);

//静态创建互斥锁
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int main(int argc, char *argv[])
{
	//三个线程id
	pthread_t tid1;
	pthread_t tid2;
	pthread_t tid3;
	//三个线程参数
	int arg1 = 1;
	int arg2 = 2;
	int arg3 = 3;
	//三个线程返回值
	void *ret1;
	void *ret2;
	void *ret3;

	if ((fp = fopen("test.txt", "a+")) == NULL)
	{
		perror("fopen");
	}

	//创建三个线程
	pthread_create(&tid1, NULL, wrfunc1, &arg1);
	sleep(2);
	pthread_create(&tid2, NULL, wrfunc2, &arg2);
	sleep(2);
	pthread_create(&tid3, NULL, wrfunc3, &arg3);
	sleep(2);

	//延长休眠时间,保证三个线程都有机会执行
	sleep(100);

	//取消线程
	pthread_cancel(tid1);
	pthread_cancel(tid2);
	pthread_cancel(tid3);

	//回收线程
	pthread_join(tid1, &ret1);
	pthread_join(tid2, &ret2);
	pthread_join(tid3, &ret3);

	return 0;
}

void *wrfunc1(void *arg)
{	
	char str[] = "I am thread1, I write a line\n"; //线程要写入文件的字符串
	int i;
	
	printf("this is thread%d\n", *(int*)arg);
	while (1)
	{
		pthread_mutex_lock(&mutex); //加入互斥锁
		
		//按字符将字符串循环写入文件
		for (i = 0; i < strlen(str); i++)
		{
			fputc(str[i], fp);
			usleep(1);
		}
		pthread_mutex_unlock(&mutex); //释放互斥锁
		pthread_testcancel(); //设置线程取消点
	}

	sleep(10);
	pthread_exit("thread1 return"); //退出线程
}

void *wrfunc2(void *arg)
{
	char str[] = "I am thread2, I write a line\n";
	int i;

	printf("this is thread%d\n", *(int*)arg);
	while (1)
	{
		pthread_mutex_lock(&mutex);
		for (i = 0; i < strlen(str); i++)
		{
			fputc(str[i], fp);
			usleep(1);
		}
		pthread_mutex_unlock(&mutex);
		pthread_testcancel();
	}

	sleep(10);
	pthread_exit("thread2 return");
}

void *wrfunc3(void *arg)
{
	char str[] = "I am thread3, I write a line\n";
	int i;

	printf("this is thread%d\n", *(int*)arg);
	while (1)
	{
		pthread_mutex_lock(&mutex);
		for (i = 0; i < strlen(str); i++)
		{
			fputc(str[i], fp);
			usleep(1);
		}
		pthread_mutex_unlock(&mutex);
		pthread_testcancel();
	}

	sleep(10);
	pthread_exit("thread3 return");
}

总结

  • 在这个代码中,是需要加入 pthread_cancel() 函数的因为:线程函数wrfunc1、wrfunc2和wrfunc3都包含一个无限循环,循环内部没有明确的退出条件。没有明确的退出条件意味着线程函数会一直执行下去,直到程序结束或者发生了某个特殊的情况导致线程被强制终止。在这种情况下,如果没有使用pthread_cancel,线程将一直运行下去,不会自动退出。
  • 这个代码中的 sleep(100) 是必须加入的,如果不加入那么 线程 2 和 线程 3 将没有机会执行,也就看不到正确的结果。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值