多线程
加锁只能限制有一个线程使用,但不能限制当前的主线程,所以存在线程安全问题
可以使用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()函数,可以当该锁处于解锁状态无人使用时再进行加锁使用。