线程_初识线程

版权声明:私藏源代码是违反人性的罪恶行为!博客转载无需告知,学无止境。 https://blog.csdn.net/qq_41822235/article/details/83474075

 从图1 我们应该能够推测出,同一进程中的所有线程所对应的进程ID将会是一样的,而各个线程ID是不同的。做一个小实验来验证一下吧。

图1 进程与线程关系示意图

代码验证 

#include<stdio.h>		//printf()
#include<pthread.h>		
#include<unistd.h>		//sleep()

void* thr_fun1(void* arg)
{
    pthread_t tid;
    tid = pthread_self();
    printf("thr_fun1 thread: pid = %lu, tid = 0x%lx\n",
        (unsigned long)getpid(),(unsigned long)tid);
}

int main()
{
    pthread_t tid;
    int err;
    err = pthread_create(&tid, NULL, thr_fun1, NULL);
    if(0 != err)
	    printf("can't create thread\n");
    printf("main thread: pid = %lu, tid = 0x%lx\n",	
	    (unsigned long)getpid(),(unsigned long)pthread_self());
    pthread_exit(NULL);
}

编译

图2 编译链接生成可执行文件p1

运行:从图3我们可以看到,线程main和线程thr_fun1编号是不同的。 

图3 运行结果(linux)

猜你喜欢

转载自blog.csdn.net/qq_41822235/article/details/83474075