目录
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;