网站工信部备案流程,wordpress收费模板,文化传媒公司网站模板,网站建设规划书有哪些内容一、基础概念对比
特性进程 (Process)线程 (Thread)资源分配资源分配的基本单位#xff08;独立地址空间#xff09;共享进程资源调度单位操作系统调度单位CPU调度的最小单位创建开销高#xff08;需复制父进程资源#xff09;低#xff08;共享进程资源#xff09;通信…
一、基础概念对比
特性进程 (Process)线程 (Thread)资源分配资源分配的基本单位独立地址空间共享进程资源调度单位操作系统调度单位CPU调度的最小单位创建开销高需复制父进程资源低共享进程资源通信方式管道、共享内存、消息队列等IPC共享全局变量需同步机制隔离性内存隔离安全性高共享内存需处理竞争条件典型组成代码段数据段堆栈段PCB线程ID寄存器组栈线程控制块TCB 二、线程组成详解
1. 核心组件
struct thread_struct {pthread_t tid; // 线程ID (8字节)void* stack_base; // 栈基地址 (8字节)size_t stack_size; // 栈大小 (Linux默认8MB)void* (*start_routine)(void*); // 入口函数指针void* arg; // 入口函数参数// 寄存器组保存区 (约52个寄存器约416字节)// 包括PC、SP、通用寄存器、浮点寄存器等
};2. 关键特征
线程IDpthread_t 类型进程内唯一独立栈空间每个线程拥有独立调用栈共享资源全局变量、堆内存、文件描述符等 三、线程创建与管理
1. 创建函数原型
#include pthread.h
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine)(void *), void *arg);参数详解表
参数类型作用说明threadpthread_t*输出参数存储新线程IDattrpthread_attr_t*线程属性NULL使用默认属性br▪ 栈大小br▪ 调度策略br▪ 分离状态start_routinevoid* (*)(void*)线程入口函数返回值为线程退出状态argvoid*传递给入口函数的参数
返回值
成功返回0失败返回错误码非errno值需用strerror转换 2. 编译指令
gcc program.c -lpthread -o program # 必须链接pthread库3. 线程终止方式
/* 主动退出带返回值*/
void pthread_exit(void *retval);/* 被动终止被其他线程取消*/
int pthread_cancel(pthread_t thread);注意事项
retval必须指向堆/静态存储区不能是线程栈内存主线程退出会导致进程终止即使其他线程仍在运行
四、线程终止方式详解补充
根据POSIX标准线程可通过以下四种方式终止执行
1. 显式调用退出函数
void* worker(void* arg) {// 动态分配返回值int* result malloc(sizeof(int));*result 100;// 显式退出并传递状态值pthread_exit((void*)result); // 正确堆内存// pthread_exit(local_var); // 危险栈内存会被回收
}特点
退出状态值通过pthread_join()获取必须保证返回值内存有效性推荐使用堆内存或全局变量
2. 从入口函数返回
void* worker(void* arg) {static int result 200; // 静态存储期变量return (void*)result; // 等效于 pthread_exit()
}注意
返回值类型必须为void*禁止返回局部变量地址函数退出后栈空间失效
3. 被其他线程取消
// 请求取消目标线程
pthread_cancel(tid);// 目标线程中设置取消点
void* worker(void* arg) {while(1) {pthread_testcancel(); // 手动设置取消点// 长时间工作...}return NULL;
}关键机制
取消类型行为特征设置函数PTHREAD_CANCEL_DEFERRED默认在下一个取消点终止pthread_setcanceltype()PTHREAD_CANCEL_ASYNCHRONOUS立即终止可能破坏数据一致性pthread_setcanceltype()
4. 进程级终止
void* thread_func(void* arg) {sleep(1);printf(此消息不会被打印\n);return NULL;
}int main() {pthread_t tid;pthread_create(tid, NULL, thread_func, NULL);// 错误示范主线程直接返回// return 0; // 导致所有线程立即终止// 正确做法主线程等待子线程pthread_exit(NULL); // 仅退出主线程不影响其他线程
}重要规则
exit()会终止整个进程及其所有线程主线程return会隐式调用exit()建议主线程使用pthread_exit()代替return 五、线程状态回收机制
1. 等待线程终止
void* status;
int ret pthread_join(tid, status);if (ret 0) {printf(线程退出码%d\n, *(int*)status);free(status); // 清理堆内存
} else {perror(等待线程失败);
}2. 分离线程自动回收
// 创建时设置分离属性
pthread_attr_t attr;
pthread_attr_init(attr);
pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED);
pthread_create(tid, attr, worker, NULL);// 或运行时分离
pthread_detach(tid);
//注意在建立线程后就设置分离特性
分离线程终止后自动回收资源无法使用pthread_join()获取状态适用于不需要返回值的后台任务 六、线程终止流程图解
graph TDA[线程开始] -- B{终止方式}B --|pthread_exit| C[传递状态值]B --|return| CB --|pthread_cancel| D[清理处理程序]B --|exit| E[终止所有线程]C -- F[状态值存储]D -- G[调用清理栈函数]F -- H[pthread_join获取]G -- I[资源释放]E -- J[进程终止]style C fill:#c9f,stroke:#333style D fill:#f96,stroke:#333style E fill:#f00,stroke:#333七、最佳实践建议 资源管理三原则 谁分配谁释放退出前释放非共享资源使用pthread_cleanup_push()注册清理函数 取消安全设计 void cleanup(void* arg) {printf(清理资源%p\n, arg);free(arg);
}void* worker(void* arg) {void* res malloc(1024);pthread_cleanup_push(cleanup, res);// 可能被取消的代码区while(1) {pthread_testcancel();// 关键操作...}pthread_cleanup_pop(1); // 执行清理return NULL;
}状态值传递规范 简单状态码使用int类型转换 pthread_exit((void*)(intptr_t)error_code);复杂数据结构使用堆内存 struct Result* res malloc(sizeof(struct Result));
/* 填充数据 */
pthread_exit(res);
4.练习 练习1创建一个线程
#includestdio.h
#includepthread.h
#includeerrno.h
#includeunistd.hvoid * do_something(void *arg)
{printf(do copy file---\n);return NULL;
}int main(int argc, const char *argv[])
{pthread_t tid;int ret;if((ret pthread_create(tid,NULL,do_something,NULL)) ! 0){errno ret;perror(pthread_create fail);return -1;}printf(-----main-------\n);sleep(1);return 0;return 0;
} 练习2创建多个线程
#includestdio.h
#includepthread.h
#includeerrno.h
#includeunistd.hvoid * do_one(void *arg)
{printf(pthread 1 pid %d\n,getpid());return NULL;
}void * do_two(void *arg)
{printf(pthread 2 pid %d\n,getpid());return NULL;
}void * do_three(void *arg)
{printf(pthread 3 pid %d\n,getpid());return NULL;
}typedef void *(*thread_cb_t)(void*);int main(int argc, const char *argv[])
{printf(---main--- pid %d\n,getpid());pthread_t tid[3];int ret;thread_cb_t func[3] {do_one,do_two,do_three};int i 0;for(i 0;i 3;i){if((ret pthread_create(tid[i],NULL,func[i],NULL)) ! 0){errno ret;perror(pthread1_create fail);return -1;}}sleep(1);return 0;return 0;
} 练习3线程的关闭
#includestdio.h
#includepthread.h
#includeerrno.h
#includeunistd.hvoid * do_something(void *arg)
{static int ret 100;printf(do copy file---\n);//pthread_exit(i am dead\n);pthread_exit(ret);//return NULL;
}int main(int argc, const char *argv[])
{pthread_t tid;int ret;if((ret pthread_create(tid,NULL,do_something,NULL)) ! 0){errno ret;perror(pthread_create fail);return -1;}printf(-----main-------\n);int *retval;//char *retval;pthread_join(tid,(void **)retval);//printf(*retval %s\n,retval);printf(*retval %d\n,*retval);sleep(1);return 0;return 0;
} 练习4多线程拷贝文件缺陷当文件过大会导致偏移量出错
#include stdio.h
#include pthread.h
#include fcntl.h
#include errno.h
#include sys/stat.h
#include unistd.htypedef struct
{int fd_s;int fd_d;int size;int len;int id;
}msg_t;void * do_copy (void *arg)
{msg_t p *(msg_t*)arg;lseek(p.fd_s,p.size*p.id,SEEK_SET);lseek(p.fd_d,p.size*p.id,SEEK_SET);// printf(tid %ld id %d fd_s %d fd_d %d size %d len %d\n,pthread_self(),p.id,p.fd_s,p.fd_d,p.size,p.len);//调试代码char buf[p.len];int ret read(p.fd_s,buf,p.len);write(p.fd_d,buf,ret);return NULL;
}//cp src dest
int main(int argc, const char *argv[])
{if (argc!3){printf(Usage: %s src dest\n,argv[0]);return -1;}int fd_s open(argv[1],O_RDONLY);int fd_d open(argv[2],O_WRONLY|O_TRUNC|O_CREAT,0666);if (fd_s 0 || fd_d 0){perror(open fail);return -1;}int n 0;printf(Input threads num: );scanf(%d,n);int i 0;int ret 0;pthread_t tid[n];msg_t msg[n];struct stat st;if (stat(argv[1],st) 0){perror(stat fail);return -1;}int f_len st.st_size;for (i 0; i n; i){msg[i].fd_s fd_s;msg[i].fd_d fd_d;msg[i].size f_len / n;msg[i].id i;#if 1if (i n-1){ msg[i].len f_len - (f_len/n)*(n-1);}else {msg[i].len f_len/n;}
#endifret pthread_create(tid[i],NULL,do_copy,msg[i]);if (ret ! 0){errno ret;perror(pthread_create fail);return -1;}}printf(----main-----\n);for (i 0; i n; i)pthread_join(tid[i],NULL);close(fd_s);close(fd_d);return 0;
}八、线程生命周期管理
1. 线程属性设置示例
pthread_attr_t attr;
pthread_attr_init(attr);
pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED); // 分离属性
pthread_attr_setstacksize(attr, 2*1024*1024); // 设置2MB栈2. 线程同步机制
机制用途相关函数互斥锁保护共享资源pthread_mutex_*系列条件变量线程间事件通知pthread_cond_*系列读写锁读写操作分离pthread_rwlock_*系列信号量控制并发访问数量sem_*系列 九、典型问题与解决方案
1. 资源竞争问题
场景多个线程同时修改全局变量 解决
pthread_mutex_t mutex PTHREAD_MUTEX_INITIALIZER;void* counter_thread(void* arg) {for(int i0; i100000; i) {pthread_mutex_lock(mutex);global_counter;pthread_mutex_unlock(mutex);}return NULL;
}2. 僵尸线程问题
现象已终止但未回收的线程占用系统资源 解决方案
使用pthread_join阻塞回收 void* retval;
pthread_join(tid, retval); // 类似进程的waitpid
free(retval); // 清理返回值或设置分离属性 pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED); 文章转载自: http://www.morning.dnhdp.cn.gov.cn.dnhdp.cn http://www.morning.ymhzd.cn.gov.cn.ymhzd.cn http://www.morning.drswd.cn.gov.cn.drswd.cn http://www.morning.dpdr.cn.gov.cn.dpdr.cn http://www.morning.zpstm.cn.gov.cn.zpstm.cn http://www.morning.xkjrq.cn.gov.cn.xkjrq.cn http://www.morning.jcffp.cn.gov.cn.jcffp.cn http://www.morning.cfocyfa.cn.gov.cn.cfocyfa.cn http://www.morning.bnbzd.cn.gov.cn.bnbzd.cn http://www.morning.kydrb.cn.gov.cn.kydrb.cn http://www.morning.zlzpz.cn.gov.cn.zlzpz.cn http://www.morning.bfnbn.cn.gov.cn.bfnbn.cn http://www.morning.syrzl.cn.gov.cn.syrzl.cn http://www.morning.nhpmn.cn.gov.cn.nhpmn.cn http://www.morning.nbmyg.cn.gov.cn.nbmyg.cn http://www.morning.dpgdj.cn.gov.cn.dpgdj.cn http://www.morning.lbgsh.cn.gov.cn.lbgsh.cn http://www.morning.mmjqk.cn.gov.cn.mmjqk.cn http://www.morning.kzcfr.cn.gov.cn.kzcfr.cn http://www.morning.kpcky.cn.gov.cn.kpcky.cn http://www.morning.npbgj.cn.gov.cn.npbgj.cn http://www.morning.jzlkq.cn.gov.cn.jzlkq.cn http://www.morning.jpgfx.cn.gov.cn.jpgfx.cn http://www.morning.hffpy.cn.gov.cn.hffpy.cn http://www.morning.mftdq.cn.gov.cn.mftdq.cn http://www.morning.wdply.cn.gov.cn.wdply.cn http://www.morning.ltffk.cn.gov.cn.ltffk.cn http://www.morning.iuibhkd.cn.gov.cn.iuibhkd.cn http://www.morning.dtlqc.cn.gov.cn.dtlqc.cn http://www.morning.mwmtk.cn.gov.cn.mwmtk.cn http://www.morning.gbnsq.cn.gov.cn.gbnsq.cn http://www.morning.lxjcr.cn.gov.cn.lxjcr.cn http://www.morning.zqbrw.cn.gov.cn.zqbrw.cn http://www.morning.msfqt.cn.gov.cn.msfqt.cn http://www.morning.pmptm.cn.gov.cn.pmptm.cn http://www.morning.wwklf.cn.gov.cn.wwklf.cn http://www.morning.dbphz.cn.gov.cn.dbphz.cn http://www.morning.dnmgr.cn.gov.cn.dnmgr.cn http://www.morning.dpbdq.cn.gov.cn.dpbdq.cn http://www.morning.qdcpn.cn.gov.cn.qdcpn.cn http://www.morning.ttnfc.cn.gov.cn.ttnfc.cn http://www.morning.jxscp.cn.gov.cn.jxscp.cn http://www.morning.mfnsn.cn.gov.cn.mfnsn.cn http://www.morning.trjr.cn.gov.cn.trjr.cn http://www.morning.zlces.com.gov.cn.zlces.com http://www.morning.zztkt.cn.gov.cn.zztkt.cn http://www.morning.pmjw.cn.gov.cn.pmjw.cn http://www.morning.wkxsy.cn.gov.cn.wkxsy.cn http://www.morning.bhmnp.cn.gov.cn.bhmnp.cn http://www.morning.wmhqd.cn.gov.cn.wmhqd.cn http://www.morning.rwzc.cn.gov.cn.rwzc.cn http://www.morning.zkzjm.cn.gov.cn.zkzjm.cn http://www.morning.flpjy.cn.gov.cn.flpjy.cn http://www.morning.pwgzh.cn.gov.cn.pwgzh.cn http://www.morning.grqlc.cn.gov.cn.grqlc.cn http://www.morning.brtxg.cn.gov.cn.brtxg.cn http://www.morning.tjpmf.cn.gov.cn.tjpmf.cn http://www.morning.nyqm.cn.gov.cn.nyqm.cn http://www.morning.zqbrw.cn.gov.cn.zqbrw.cn http://www.morning.sqnrz.cn.gov.cn.sqnrz.cn http://www.morning.ttkns.cn.gov.cn.ttkns.cn http://www.morning.wtcyz.cn.gov.cn.wtcyz.cn http://www.morning.zfqr.cn.gov.cn.zfqr.cn http://www.morning.wwznd.cn.gov.cn.wwznd.cn http://www.morning.qhjkz.cn.gov.cn.qhjkz.cn http://www.morning.sffkm.cn.gov.cn.sffkm.cn http://www.morning.xnflx.cn.gov.cn.xnflx.cn http://www.morning.hnrpk.cn.gov.cn.hnrpk.cn http://www.morning.jjhng.cn.gov.cn.jjhng.cn http://www.morning.hcwjls.com.gov.cn.hcwjls.com http://www.morning.hgfxg.cn.gov.cn.hgfxg.cn http://www.morning.zgqysw.cn.gov.cn.zgqysw.cn http://www.morning.bchgl.cn.gov.cn.bchgl.cn http://www.morning.jjxnp.cn.gov.cn.jjxnp.cn http://www.morning.tldhq.cn.gov.cn.tldhq.cn http://www.morning.rkfh.cn.gov.cn.rkfh.cn http://www.morning.dtlnz.cn.gov.cn.dtlnz.cn http://www.morning.fpbj.cn.gov.cn.fpbj.cn http://www.morning.tbjtp.cn.gov.cn.tbjtp.cn http://www.morning.wmdqc.com.gov.cn.wmdqc.com