多线程不能调用strtok
函数,它内部是用一个静态全局变量来记住当前位置,所以在main函数结束之前,线程和主函数用的是一个strtok,因此是错误的,下面是错误的代码。
#include<stdio.h>
#include<stdlib.h>
#include<>string.h
#include<semaphore.h>
#include<pthread.h>
void* fun(void* arg)
{
char arr[128]={"1 2 3 4 5 6 7 8 9"};
char* s=strtok(arr," ");
while(s!=NULL)
{
printf("fun s=%s\n",s);
sleep(1);
s=strtok(NULL," ");
}
}
int main()
{
pthread_t id;
pthread_create(&id,NULL,fun,NULL);
char buf[128]={"a b c d e f g h"};
char* s=strtok(buff," ");
while(s!=NULL)
{
printf("main s=%s\n",s);
sleep(1);
s=strtok(NULL," ");
}
pthread_join(id,NULL);
exit(0);
}
strtok_r
是为了解决上面的问题实现的,各自记住各自分割在哪
#include<stdio.h>
#include<stdlib.h>
#include<>string.h
#include<semaphore.h>
#include<pthread.h>
void* fun(void* arg)
{
char arr[128]={"1 2 3 4 5 6 7 8 9"};
char* ptr=NULL;
char* s=strtok_r(arr," ",&ptr);将指针ptr传进去改变指向的位置
while(s!=NULL)
{
printf("fun s=%s\n",s);
sleep(1);
s=strtok_r(NULL," ",&ptr);
}
}
int main()
{
pthread_t id;
pthread_create(&id,NULL,fun,NULL);
char buf[128]={"a b c d e f g h"};
char* ptr=NULL;
char* s=strtok_r(buff," ",&ptr);
while(s!=NULL)
{
printf("main s=%s\n",s);
sleep(1);
s=strtok_r(NULL," ",&ptr);
}
pthread_join(id,NULL);
exit(0);
}
读写锁
读写锁可以共享读
,而互斥锁不可以。
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<unistd.h>
pthread_rwlock_t rwlock;
void* read_fun1(void* arg)
{
while(1)
{
pthread_rwlock_rdlock(&rwlock);读锁
printf("read1 start\n");
sleep(1);
printf("read1 end\n");
pthread_rwlock_unlock(&rwlock);
sleep(1);
}
}
void* read_fun2(void*)
{
while(1)
{
pthraed_rwlock_rdlock(&rwlock);
printf("read2 start\n");
sleep(1);
printf("read2 end\n");
pthread_rwlock_unlock(&rwlock);
sleep(1);
}
}
void* write_fun(void* arg)
{
while(1)
{
pthread_rwlock_wrlock(&rwlock);
printf("write start\n");
sleep(3);
printf("write end\n");
pthread_rwlock_unlock(&rwlock);
sleep(1);
}
}
int main()
{
pthread_rwlock_init(&rwlock,NULL);
pthread_t idr1,idr2;
pthread_create(&idr1,NULL,read_fun1,NULL);
pthread_create(&idr2,NULL,read_fun2,NULL);
pthread_create(&idw,NULL,write_fun,NULL);
pthread_join(idr1,NULL);
pthread_join(idr2,NULL);
pthread_join(idw,NULL);
pthread_rwlock_destroy(&rwlock);
}