admin 管理员组

文章数量: 887021


2024年1月18日发(作者:程序源代码论坛网站)

#include #include #include #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 #include #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(); }


本文标签: 信号量 创建 线程