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

    结论:

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

  • 相关阅读:
    String、StringBuilder、StringBuffer的比较
    applet、servlet、jsp分别是什么
    getWriter() has already been called for this response 的解决办法
    servlet 的作用
    什么是 servlet?
    jsp的Session 和Servlet的Session的区别
    java——复用代码、组合、继承(java编程思想)
    Java----访问权限
    CountDownLatch源码分析
    Redis底层数据结构之 zset
  • 原文地址:https://www.cnblogs.com/jacklikedogs/p/3957678.html
Copyright © 2011-2022 走看看