我想製作一個程序,用2個函數寫1到100之間的奇數和偶數,第一個函數打印前5個奇數,第二個函數打印前5個偶數,再次打印返回第一個函數打印第二個5個奇數,依此類推。 在這個程序中,我想僅在2
線程之間交替,但我找不到解決方案。這裏是我的代碼,在這段代碼中,我創建了40
個線程。有誰知道如何在2個線程之間交替並找到相同的輸出。2個線程之間的交替
#include<stdio.h>
#include<pthread.h>
pthread_t tid[40];
int pair=2;
int impair=1 ;
pthread_mutex_t lock;
void* genpair(void *arg)
{
pthread_mutex_lock(&lock);
int i = 0;
for (i=0 ; i<5 ; i++,pair+=2)
{
printf("%d ",pair) ;
}
printf(" ");
pthread_mutex_unlock(&lock);
return NULL;
}
void* genimpair(void *arg)
{
pthread_mutex_lock(&lock);
int i = 0;
for (i=0 ; i<5 ; i++,impair+=2)
{
printf("%d ",impair) ;
}
printf(" ");
pthread_mutex_unlock(&lock);
return NULL;
}
int main(void)
{
int i = 0;
int j=0 ;
int err;
if (pthread_mutex_init(&lock, NULL) != 0)
{
printf("\n mutex init failed\n");
return 1;
}
for(j=0 ; j<20 ; j+=2)
{
pthread_create(&(tid[j]), NULL, &genpair, NULL);
pthread_create(&(tid[j+1]), NULL, &genimpair, NULL);
pthread_join(tid[j], NULL);
pthread_join(tid[j+1], NULL);
}
pthread_mutex_destroy(&lock);
return 0;
}
請描述你的程序的當前行爲。但對於初學者來說,在'pthread_mutex_unlock'之前放置一個'printf(「\ n」)'來刷新緩衝輸出,以便它出現在stdout上。 – kaylum
使用線程完成任務毫無意義。 – nwp
@nwp如果這是一個學習練習。或者,如果它是從更大的程序派生的MCVE。 – kaylum