【多线程】【C++ 知识点】pthread_join学习
pthread_join
-
pthread_join() 主线程会进入阻塞装题,pthread_join()之后的代码,只有等待子进程退出之后才能执行。
代码块A
pthread_create(&id, NULL, Fn, NULL); pthread_create(&id_1, NULL, Fn, NULL); pthread_join(id, NULL); pthread_join(id_1, NULL);
代码块B
pthread_create(&id, NULL, Fn, NULL); pthread_join(id, NULL); pthread_create(&id_1, NULL, Fn, NULL); pthread_join(id_1, NULL);
代码块A和代码块B,执行的输出情况不同,证明pthread_join会阻塞主线程。当A线程调用线程B并 pthread_join() 时,A线程会处于阻塞状态,直到B线程结束后,A线程才会继续执行下去。当 pthread_join() 函数返回后,被调用线程才算真正意义上的结束,它的内存空间也会被释放(如果被调用线程是非分离的)。这里有几点需要注意:
- 必须手动清除程序分配的空间,被释放的内存空间仅仅是系统空间,比如 malloc() 分配的空间。
所以可以看出pthread_join()有两种作用: 2. 用于等待其他线程结束:当调用 pthread_join() 时,当前线程会处于阻塞状态,直到被调用的线程结束后,当前线程才会重新开始执行。 3. 获取线程执行的返回值
void *__start_routine(void *){ ..... ..... return retval; } pthread_create(&id, NULL, __start_routine, args); void *retval_B = NULL; pthread_join(id_B, &retval_B); //得到线程执行的返回值 value int value = *(int *)retval_B;
static int count = 0; void *Fn(void *) { for (int i = 0; i < 5; i++) { count++; } sleep(2); printf("count :%d ", count); return NULL; } int main(int argc, char **argv) { pthread_t id; pthread_create(&id, NULL, Fn, NULL); // pthread_join(id, NULL); printf("count :%d ", count); return 0; }
进程id和线程id
分不清哪个是进程ID、哪个是线程ID?
#include <cstdio> #include <pthread.h> #include <sys/syscall.h> #include <unistd.h> static int count = 0; #define gettidv1() syscall(__NR_gettid) // new form #define gettidv2() syscall(SYS_gettid) // traditional form void *Fn(void *) { for (int i = 0; i < 5; i++) { count++; } sleep(5); printf("count :%d pid : %d ppid : %d self: %ld LWPID/tid: %ld ", count, getpid(), getppid(), pthread_self(), gettidv1()); return NULL; } void Run() { pthread_t id, id_1; pthread_create(&id, NULL, Fn, NULL); pthread_create(&id_1, NULL, Fn, NULL); pthread_join(id, NULL); pthread_join(id_1, NULL); } int main(int argc, char **argv) { Run(); printf(" 啦啦啦啦拉 我是大好人 count :%d ", count); return 0; }
执行结果:
count :10 pid : 28160 ppid : 17831 self: 139782427522816 LWPID/tid: 28162 count :10 pid : 28160 ppid : 17831 self: 139782435915520 LWPID/tid: 28161 啦啦啦啦拉 我是大好人 count :10
ps -ef |grep 26773 & top -H -p 26773命令查询子线程结果:
lionel 28160 27646 0 14:04 pts/4 00:00:00 ./a.out lionel 28180 25566 0 14:04 pts/2 00:00:00 grep --color=auto a.out
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 28160 lionel 20 0 19044 620 532 S 0.0 0.0 0:00.00 a.out 28161 lionel 20 0 19044 620 532 S 0.0 0.0 0:00.00 a.out 28162 lionel 20 0 19044 620 532 S 0.0 0.0 0:00.00 a.out
-
getpid() 即进程id。 获取process id 或 PID of the calling process 。 getppid() 即父进程id。 获取执行进程的父进程the parent process 。 pthread_self()即线程id,内核不认识。 pthread_self它返回一个 pthread_t 类型的变量,指代的是调用 pthread_self 函数的线程的 “ID”。这个“ID”是 pthread 库给每个线程定义的进程内唯一标识,是 pthread 库维持的。由于每个进程有自己独立的内存空间,故此“ID”的作用域是进程级而非系统级(内核不认识)。 syscall(__NR_gettid)即线程id。(轻量级进程LWP) LWPID/tid
参考:
上一篇:
通过多线程提高代码的执行效率例子
下一篇:
Windows 常用web站点搭建