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\n";
                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

结论:

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

 

posted @ 2014-09-05 11:25  咚咚锵锵  阅读(440)  评论(0编辑  收藏  举报