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);
     }
}
相关推荐
Ronin30528 分钟前
【C++】类型转换
开发语言·c++
mrbone1144 分钟前
Git-git worktree的使用
开发语言·c++·git·cmake·worktree·gitab
浪裡遊1 小时前
Sass详解:功能特性、常用方法与最佳实践
开发语言·前端·javascript·css·vue.js·rust·sass
真实的菜1 小时前
JVM类加载系统详解:深入理解Java类的生命周期
java·开发语言·jvm
代码讲故事1 小时前
多种方法实现golang中实现对http的响应内容生成图片
开发语言·chrome·http·golang·图片·快照·截图
chanalbert2 小时前
CentOS系统新手指导手册
linux·运维·centos
星宸追风2 小时前
Ubuntu更换Home目录所在硬盘的过程
linux·运维·ubuntu
虾球xz2 小时前
CppCon 2018 学习:EFFECTIVE REPLACEMENT OF DYNAMIC POLYMORPHISM WITH std::variant
开发语言·c++·学习
Allen_LVyingbo2 小时前
Python常用医疗AI库以及案例解析(2025年版、上)
开发语言·人工智能·python·学习·健康医疗
小哈龙2 小时前
裸仓库 + Git Bash 搭建 本地 Git 服务端与客户端
开发语言·git·bash