2015-10-17 33 views
0

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

样例程序:

#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; 
} 
+0

你知道互斥吗?您可以定义一个公共变量来衡量时间,但要正确访问它,您需要同步这些线程。 –

+0

代码甚至没有编译,你为什么要发布这样的东西?此外,为什么有必要创建一个线程数组呢?你的问题与此完全无关。最后,你正在创建比你加入的更多的线程,这是另一个问题。 –

回答

0

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

1

而不是等待线程pthread_join您可以将main线程休眠,例如nanosleep。如果您没有加入,则退出main,您的整个过程将被终止。