Linux——多线程线程安全

多线程
加锁只能限制有一个线程使用,但不能限制当前的主线程,所以存在线程安全问题
可以使用strtok_r()方法

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

void * fun(void * arg)
{
	char buff [] = "1 2 3 4 5 7 8 9 10";
	char * ptr = NULL;
	char * s = strock_r(buff," ",&ptr);
	printf("fun s=%s\n",s);
	sleep(1);	

	while((s = strock_r(NULL," ",&ptr)) !=NULL)
	{
		printf("fun s=%s\n",s);
		sleep(1);
	}
	pthread_exit(NULL);
}

int main()
{
	pthread_t id;
	pthread_creat(&id,NULL,fun,NULL);
	char buff [] = "a b c d e f w r t y";
	char * ptr = NULL;
	char * s = strock_r(buff," ",&ptr);
	printf("main s=%s\n",s);
	sleep(1);
	while((s = strock_r(NULL," ",&ptr)) !=NULL)
	{
		printf("main s=%s\n",s)
		sleep(1);
	}
	pthread_join(id,NULL);
	exit(0);
}

多线程
可以创建多少个线程
查看所有后台大小限制 ulimit -a
改变线程限制 ulimit -u …

子线程函数中加了一把锁,此时fork一个进程时,这把锁处于加锁状态,在子进程中这把锁也处于加锁状态;若这把锁处于解锁状态,则子进程中也属于解锁状态。

但是不能直接对加锁状态进行解锁,会引发数据安全问题,可以使用pthread_atfork()函数,可以当该锁处于解锁状态无人使用时再进行加锁使用。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

有头发的小小猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值