线程安全——使用线程安全函数,多线程中执行fork引发的问题及如何解决

目录

一、引例

二、线程安全

三、多线程中执行fork

3.1 多线程中某个线程调用 fork(),子进程会有和父进程相同数量的线程吗?

3.2 父进程被加锁的互斥锁 fork 后在子进程中是否已经加锁


一、引例

在主线程和函数线程中进行语句分割并输出。

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

void* thread_fun(void* arg)
{
	char buff[128]={"a b c d e f g h w q"};
	char* s=strtok(buff," ");
	while(s!=NULL)
	{
		printf("thread:s=%s\n",s);
		sleep(1);
		s=strtok(NULL," ");
	}
}

int main()
{
	pthread_t id;
	pthread_create(&id,NULL,thread_fun,NULL);
	char str[128]={"1 2 3 4 5 6 7 8 9 10"};
	char* s=strtok(str," ");
	while(s!=NULL)
	{
		printf("main:%s\n",s);
		sleep(1);
		s=strtok(NULL," ");
	}
	pthread_join(id,NULL);
	exit(0);
}

因为strtok函数不是线程安全的,因为它使用了静态变量或者全局变量。

只要使用全局变量或者静态变量的函数,在多线程中都不能使用。这些函数都不是线程安全的。

不可重入:当程序被多个线程反复调用,产生的结果会出错。

strtok_r函数是线程安全的

更改后代码:

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

void* thread_fun(void* arg)
{
	char buff[128]={"a b c d e f g h w q"};
	char* ptr=NULL;
	char* s=strtok_r(buff," ",&ptr);
	while(s!=NULL)
	{
		printf("thread:s=%s\n",s);
		sleep(1);
		s=strtok_r(NULL," ",&ptr);
	}
}

int main()
{
	pthread_t id;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值