2010-05-04 131 views
0

我想完成10次,掃描號碼並重新打印。我怎樣才能做到這一點?線程問題

#include <stdio.h> 

#include <pthread.h> 
#include <semaphore.h> 

sem_t m; 
int n; 

void *readnumber(void *arg) 
{ 
     scanf("%d",&n); 
     sem_post(&m); 
} 

void *writenumber(void *arg) 
{ 
    //int x =3; 
    //while(x>0) 
    //{ 
     //x = x-1; 
     sem_wait(&m); 
     printf("%d",n); 

    //} 
} 

int main(){ 
    pthread_t t1, t2; 
    sem_init(&m, 0, 0); 
    pthread_create(&t2, NULL, writenumber, NULL); 
    pthread_create(&t1, NULL, readnumber, NULL); 
    pthread_join(t2, NULL); 
    pthread_join(t1, NULL); 
    sem_destroy(&m); 
    return 0; 
} 
+1

我不確定這種情況是否足夠迫切以保證多個感嘆號。 – Syntactic 2010-05-04 11:59:47

+1

需要'家庭作業'標籤? – 2010-05-04 12:03:20

+0

double post:http://stackoverflow.com/questions/2764696/c-threads-question – KillianDS 2010-05-04 12:23:47

回答

3

我不完全知道你是問什麼,但一般來說,如果你想要的東西發生的特定次數,要使用一個for循環,就像這樣:

for(int i = 0; i < 10; i++) { 
//whatever you want to happen 10 times goes here 
} 

我感到困惑的原因是,有人想知道如何在不知道for循環是什麼的情況下如何創建POSIX線程有點奇怪。