2015-10-17 65 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,您的整個過程將被終止。