您的位置:首页 > 运维架构 > Linux

多线程的一种场景

2017-07-08 11:09 141 查看

多线程执行一段程序

void* say_hello(void* args)
{
int tid = *((int*)args);

printf("i = %d\n", tid);
//printf("process yuv %s  h264 %s\n",yuv_input[i].c_str(),h264_output[i].c_str());

}

// 线程的运行函数,函数返回的是函数指针,便于后面作为参数
// 定义线程的 id 变量,多个变量使用数组
pthread_t tids[NUM_THREADS];
int indexes[NUM_THREADS];// 用数组来保存i的值

for(int i = 0; i < process_no; ++i)
{
indexes[i] = i; //先保存i的值

//参数依次是:创建的线程id,线程参数,调用的函数,传入的函数参数
int ret = pthread_create(&tids[i], NULL, say_hello, (void *)&(indexes[i]));
if (ret != 0)
{
std::cout << "pthread_create error: error_code=" << ret << std::endl;
}
}
//等各个线程退出后,进程才结束,否则进程强制结束了,线程可能还没反应过来;
void *status;
for( int i = 0; i < process_no; ++i )
{
int ret = pthread_join( tids[i], &status ); //主程序join每个线程后取得每个线程的退出信息status
if( ret != 0 )
{
std::cout << "pthread_join error:error_code=" << ret << std::endl;
}
}
//pthread_exit(NULL);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息