zoukankan      html  css  js  c++  java
  • 1个争用资源的简单线程小例子

    main()本身就是一线程,现在在main内部再创建另一个线程,

    例子只是简单的在两个线程中打印了一下TID和PID以及获取本身PID,当然两个线程的TID是一样的,PID是不一样的。

    这里主要说的是:两个线程一起运行,屏幕上显示的各线程的内容,因为一起争用资源,造成了打印信息内容的重叠。

    代码:

    #include <iostream>
    #include <unistd.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>
    using namespace std;
    void *thread_func(void *arg);
    
    pthread_t tid;
    
    void *thread_func(void *arg)
    {
            cout<<"NewThread : PID="<<getpid()<<", TID="<<tid<<", pthread_self()="<<pthread_self()<<endl;
            pthread_exit(NULL); //退出线程(actived)
    }
    
    int main()
    {
            //pthread_t tid;
            if (pthread_create(&tid, NULL, thread_func, NULL) != 0)
            {
                    cout<<"Create thread error
    ";
                    exit(1);
            }
            cout<<"MainThread: PID="<<getpid()<<", TID="<<tid<<", pthread_self()="<<pthread_self()<<endl;
    
            sleep(2);
            return 0;
    }

    输出结果:

    [root@localhost thread]# ./a.out 

    MainThread: PID=NewThread : PID=5597155971, TID=, TID=139748750608128, pthread_self()=139748750608128139748750616352, pthread_self()=139748750608128

    [root@localhost thread]# ./a.out
    MainThread: PID=56049, TID=140537922148096, pthread_self()=140537922156320NewThread : PID=56049, TID=
    140537922148096, pthread_self()=140537922148096


    [root@localhost thread]# ./a.out
    MainThread: PID=56053, TID=140158878066432, pthread_self()=140158878074656
    NewThread : PID=56053, TID=140158878066432, pthread_self()=140158878066432

    结论:

    在多线程中使用同一资源时,如果线程的执行过程不是原子操作,那么它在执行过程中随时会被其它线程中断,然后等到其再拥有资源权限时,再继续执行剩下的操作。

  • 相关阅读:
    Java集合源码分析(一)
    EffectiveJava——请不要在代码中使用原生态类型
    Dubbo初探
    EffectiveJava——用函数对象表示策略
    EffectiveJava——类层次优于标签类
    notebook1.md
    NoteBook学习(二)-------- Zeppelin简介与安装
    Spark2.0学习(三)--------核心API
    Spark2.0学习(二)--------RDD详解
    Spark2.0学习(一)--------Spark简介
  • 原文地址:https://www.cnblogs.com/jacklikedogs/p/3957678.html
Copyright © 2011-2022 走看看