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);
     }
}
相关推荐
没有晚不了安5 分钟前
1.13作业
开发语言·python
布谷歌9 分钟前
Oops! 更改field的数据类型,影响到rabbitmq消费了...(有关于Java序列化)
java·开发语言·分布式·rabbitmq·java-rabbitmq
被程序耽误的胡先生15 分钟前
java中 kafka简单应用
java·开发语言·kafka
刀客12315 分钟前
python小项目编程-中级(1、图像处理)
开发语言·图像处理·python
卷卷的小趴菜学编程20 分钟前
c++之多态
c语言·开发语言·c++·面试·visual studio code
冷琴199640 分钟前
基于Python+Vue开发的反诈视频宣传管理系统源代码
开发语言·vue.js·python
楠枬1 小时前
网页五子棋——对战后端
java·开发语言·spring boot·websocket·spring
kyle~1 小时前
thread---基本使用和常见错误
开发语言·c++·算法
你好呀我是裤裤1 小时前
Linux基础开发工具的使用(apt、vim、gcc、g++、gdb、make、makefile)
linux·运维·vim
望获linux1 小时前
如何在望获实时 Linux & 京博航友善 NanoPC-T6 上部署 Docker
linux·运维·服务器·docker·eureka·开源软件