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);
     }
}
相关推荐
夜夜敲码17 分钟前
C语言教程(十六): C 语言字符串详解
c语言·开发语言
宋康24 分钟前
C语言结构体和union内存对齐
c语言·开发语言
꧁坚持很酷꧂30 分钟前
Linux Ubuntu18.04下安装Qt Craeator 5.12.9(图文详解)
linux·运维·qt
居然是阿宋34 分钟前
Kotlin高阶函数 vs Lambda表达式:关键区别与协作关系
android·开发语言·kotlin
凉、介1 小时前
PCI 总线学习笔记(五)
android·linux·笔记·学习·pcie·pci
Cao1234567893211 小时前
简易学生成绩管理系统(C语言)
c语言·开发语言
The Future is mine1 小时前
C# new Bitmap(32043, 32043, PixelFormat.Format32bppArgb)报错:参数无效,如何将图像分块化处理?
开发语言·c#
电鱼智能的电小鱼1 小时前
EFISH-SBC-RK3588无人机地面基准站项目
linux·网络·嵌入式硬件·机器人·无人机·边缘计算
亿坊电商1 小时前
PHP框架在微服务迁移中能发挥什么作用?
开发语言·微服务·php
烁3471 小时前
每日一题(小白)模拟娱乐篇33
java·开发语言·算法