admin 管理员组文章数量: 887021
2024年1月18日发(作者:程序源代码论坛网站)
#include
void print_message_func(void *ptr);
int main(){ int tmp1,tmp2; void *retival; pthread_t thread1,thread2; char *message1 = "thread1"; char *message2 = "thread2";
int ret_thread1,ret_thread2; ret_thread1 = pthread_create(&thread1,NULL,(void *)&print_message_func,(void *)message1);
if(ret_thread1 == 0) printf("create thread 1 truen"); else printf("create thread 1 falsen");
tmp1 = pthread_join(thread1,&retival); printf("thread 1 return value (tmp1) is %dn",tmp1);
if(tmp1 != 0) printf("cannot join with thread 1n");
ret_thread2 = pthread_create(&thread2,NULL,(void *)&print_message_func,(void *)message2);
if(ret_thread2 == 0) printf("create thread 2 truen"); else printf("create thread 2 falsen");
tmp2 = pthread_join(thread2,&retival); printf("thread 2 return value (tmp2) is %dn",tmp2); if(tmp2 != 0) printf("cannot join with thread 2n");}
void print_message_func(void *ptr){ for(int i=0;i<5;++i) { printf("%s:%dn",(char*)ptr,i); }}线程属性线程属性,在创建时分离代码:
同步机制的封装 syn_pthread.h#ifndef _SYN_PTHREAD_H_#define _SYN_PTHREAD_H_
#include
/*封装信号量*/class sem{public: sem()//创建并初始化信号量 { if(sem_init(&m_sem,0,0)!=0) { throw std::exception();//初始化函数没有返回值抛出异常 } } ~sem()//销毁信号量 { sem_destroy(&m_sem); } bool wait()//等待信号量 { return sem_wait(&m_sem)==0; } bool post()//增加信号量 { return sem_post(&m_sem)==0; }private: sem_t m_sem;};
/*封装互斥锁*/class locker{public: locker()//创建并初始化互斥锁 { if(pthread_mutex_init(&m_mutex,NULL)!=0) { throw std::exception(); }
版权声明:本文标题:【总结】Linux内核剖析---线程及其同步 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.freenas.com.cn/free/1705579119h490813.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论