Linux线程基本使用代码演示样例
2023-09-27 14:25:17 时间
#include <pthread.h> #include <stdio.h> #include <unistd.h> void* thread_func(void* param) { const char* p = (const char*)param; pid_t pid = 0; pthread_t tid = 0; pid = getpid(); tid = pthread_self(); printf("%s -> %8u %8u\n", p, (unsigned int)pid, (unsigned int)tid); } void* thread_wait_cancel(void* p) { printf("thread wait cancel -> i'm waitting for cancel\n"); sleep(10000); printf("if u saw me, there got be something wrong\n"); } int main(int argc, char* argv[]) { pthread_t tid = 0; pthread_create(&tid, NULL, thread_func, (void *)"sub thread"); pthread_t tid_cancel = 0; pthread_create(&tid_cancel, NULL, thread_wait_cancel, NULL); // wait thread tid to exit pthread_join(tid, NULL); // cancel a thread void* stat = 0; pthread_cancel(tid_cancel); pthread_join(tid_cancel, &stat); /* stat = -1 stand for PTHREAD_CANCELED */ printf("cancel thread exit state : %d\n", stat); // show main thread infomation thread_func((void *)"main thread"); return 0; }
注意编译的时候须要加上选项-lpthread。由于pthread不是linu的默认库,例如以下所看到的:
gcc thr.c -lpthread
相关文章
- linux的内核bug引起线程挂起
- 【ARM-Linux开发】【CUDA开发】【深度学习与神经网络】Jetson Tx2安装相关之一
- Linux系统编程-进程(二):进程的创建、父子进程【fork():从一个已存在的进程中创建的新进程称为子进程,原进程称为父进程】【使用 fork() 得到的子进程是父进程的复制品(深拷贝)】
- 开发一个Linux调试器(二):断点
- LINUX学习之进程线程协程
- Deepin Linux修改Grub引导
- Linux线程控制
- 给新手的 10 个有用 Linux 命令行技巧
- 【Linux】线程并发拷贝程序
- Linux多线程实践(一)线程基本概念和理论
- Linux下Java线程具体监控和其dump的分析使用----分析Java性能瓶颈[张振华-Jack]
- China Linux Kernel-ppt
- 【线程】linux之thread错误解决方案
- linux exec函数家族
- Linux下EC20实现ppp拨号(转)
- Linux下线程pid和tid
- Linux平台用C++实现事件对象,同步线程
- 如何编写Linux设备驱动程序
- 掌握 Linux 调试技术
- C-Linux_毫秒级随机值获取
- fabric执行远程Linux命令
- Linux线程同步对象:互斥体、信号量、条件变量、读写锁
- 查看Linux进程CPU过高具体的线程堆栈(不中断程序)
- Linux有问必答:Linux上如何查看某个进程的线程
- linux下如何获取每个线程的CPU占用率