16-LINUX--线程安全

一。线程安全
线程安全即就是在多线程运行的时候,不论线程的调度顺序怎样,最终的结果都是
一样的、正确的。那么就说这些线程是安全的。
要保证线程安全需要做到:
1) 对线程同步,保证同一时刻只有一个线程访问临界资源。
2)在多线程中使用线程安全的函数(可重入函数),所谓线程安全的函数指的是:如果一个
函数能被多个线程同时调用且不发生竟态条件,则我们称它是线程安全的。
不保证线程安全的代码示例:

复制代码
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>

void* PthreadFun(void *arg)
  {
     char buff[] = "a b c d e f g h i";

     char *p = strtok(buff, " ");
     while(p != NULL)
     {
 printf("fun:: %c\n", *p);
 p = strtok(NULL, " ");
 sleep(1);
     }
 }

int main()
{
    pthread_t id;
    int res = pthread_create(&id, NULL, PthreadFun, NULL);
    assert(res == 0);

    char buff[] = "1 2 3 4 5 6 7 8 9";

    char *p = strtok(buff, " ");

    while(p != NULL)
    {   
        printf("main:: %c\n", *p);
        p = strtok(NULL, " ");
        sleep(1);
    }
}

安全代码:

复制代码
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>

void* PthreadFun(void *arg)
 {
     char buff[] = "a b c d e f g h i";

     char *q = NULL;
     char *p = strtok_r(buff, " ", &q);
     while(p != NULL)
     {
        printf("fun:: %c\n", *p);
        p = strtok_r(NULL, " ", &q);
        sleep(1);
    }
}

int main()
{
     pthread_t id;
     int res = pthread_create(&id, NULL, PthreadFun, NULL);
     assert(res == 0);


     char buff[] = "1 2 3 4 5 6 7 8 9";
     char *q = NULL;
     char *p = strtok_r(buff, " ", &q);
     while(p != NULL)
     {
        printf("main:: %c\n", *p);
        p = strtok_r(NULL, " ", &q);
        sleep(1);
     }
}
相关推荐
apihz10 分钟前
随机驾考题目(C 照科一 / 科四 2000+ 题)免费API调用教程
android·java·c语言·开发语言·网络协议·tcp/ip
matlab代码34 分钟前
基于matlab人脸疲劳驾驶检测系统(可使用其它人脸视频)【源码39期】
开发语言·matlab·人脸疲劳检测
zenithdev11 小时前
fastcache:为 Go 设计的低 GC 压力内存缓存
开发语言·其他·缓存·golang
想你依然心痛1 小时前
自定义RTOS内核:从零实现上下文切换与任务调度——汇编、PendSV
java·开发语言·汇编·pendsv
hai3152475431 小时前
九章空间几何对照直译法:通用芯片 / 定制专用芯片 编译适配规则
linux·汇编·bash
ton_tom2 小时前
设备驱动程序编程-Linux2.6.10-kdb安装-32位
linux·运维·服务器
geovindu2 小时前
java:Abstract Factory Pattern
java·开发语言·后端·设计模式·抽象工厂模式·创建型模式
geovindu2 小时前
java: Factory Method Pattern
java·开发语言·后端·设计模式·工厂方法模式·创建型模式
dddwjzx2 小时前
嵌入式Linux C应用编程入门——进程 ( 二 )
linux·嵌入式
m0_587098992 小时前
Qt,二进制文件读写建议
开发语言·qt