创建时间特定的线程

时间:2015-10-17 09:38:23

标签: c multithreading pthreads

我编写了一个示例程序来实现线程数组。有两个线程函数。有没有办法定义一个固定的时间值(以秒为单位),之后所有线程都会自动停止?

示例程序:

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>


void * threadFunc1(void * arg)
{

    int id = *((int *) arg);
    printf("Inside threadfunc2 for thread %d\n",id)
    while(1);
}

void * threadFunc2(void * arg)
{
    int i= *((int *)arg);
    printf("Inside threadfunc2 for thread %d\n",i)
    while(1);
}

int main(void)
{

    pthread_t thread[10];

    for(int i=0;i<10;i++)
    {

        pthread_create(&thread[i],NULL,threadFunc1,(void*)&i ); 
        pthread_create(&thread[i],NULL,threadFunc,(void*)&i );
    }

    for (i=0;i<total;i++)
    {
          pthread_join(thread[i],NULL);
      }
    return 0;
 }

2 个答案:

答案 0 :(得分:1)

您可以将pthread_join线程置于休眠状态,而不是等待main的线程,例如使用nanosleep。如果您在没有加入的情况下退出main,那么整个过程将被终止。

答案 1 :(得分:0)

不,没有。线程不会“自动停止”

相关问题