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);
     }
}
相关推荐
平凡的小码农15 分钟前
JAVA实现大写金额转小写金额
java·开发语言
南种北李18 分钟前
Linux自动化构建工具Make/Makefile
linux·运维·自动化
小飞猪Jay24 分钟前
面试速通宝典——10
linux·服务器·c++·面试
yttandb29 分钟前
重生到现代之从零开始的C语言生活》—— 内存的存储
c语言·开发语言·生活
我明天再来学Web渗透33 分钟前
【hot100-java】【二叉树的层序遍历】
java·开发语言·数据库·sql·算法·排序算法
结衣结衣.1 小时前
python中的函数介绍
java·c语言·开发语言·前端·笔记·python·学习
茫茫人海一粒沙1 小时前
Python 代码编写规范
开发语言·python
原野心存1 小时前
java基础进阶知识点汇总(1)
java·开发语言
程序猿阿伟1 小时前
《C++高效图形用户界面(GUI)开发:探索与实践》
开发语言·c++
暗恋 懒羊羊1 小时前
Linux 生产者消费者模型
linux·开发语言·ubuntu