[英]How can I eliminate the global variables in this code?
下面的代碼創建兩個線程。 一個接受輸入,另一個同時打印文本。 根據我在該主題上所讀的內容,在傳統的c ++代碼中,全局變量被認為是錯誤的形式。 但是,我想不出一種沒有它們就可以同時進行輸入/輸出的方法。
如何從代碼中消除這兩個布爾全局變量?
bool input_done = 1;
bool output_done = 1;
void* input(void* ptr)
{
char msg[256];
cin.getline(msg,256);
cout << msg << endl;
input_done = 1;
pthread_exit(NULL);
}
void* output(void* ptr)
{
cout << "Hello World" << endl;
for(long int x=0;x<1000000000;x++) {}
output_done = 1;
pthread_exit(NULL);
}
int main()
{
while(1)
{
pthread_t t1,t2;
if (input_done)
{
pthread_create(&t1,NULL,input,NULL);
input_done = 0;
}
if (output_done)
{
pthread_create(&t2,NULL,output,NULL);
output_done = 0;
}
}
}
有些指針傳遞給您不使用的線程函數。 將指針傳遞給變量,並通過這些指針訪問它們,然后就可以在函數main
或其他任何位置的堆棧上分配變量。
因此,例如,您的output
函數看起來像
void* output(void* output_done)
{
cout << "Hello World" << endl;
for(long int x=0;x<1000000000;x++) {}
*((bool*)output_done) = 1;
pthread_exit(NULL);
}
和pthread_create
調用:
int main()
{
bool output_done = 1;
// ...
if (output_done)
{
pthread_create(&t2,NULL,output, &output_done);
output_done = 0;
}
讓input_done
和output_done
在局部變量main
,通過第四個參數傳遞指向他們的線程函數pthread_create
,並讓該線程功能修改他們通過他們收到的指針。
示例(根據樣式進行調整):
void* input(void* ptr)
{
char msg[256];
cin.getline(msg, 256);
cout << msg << endl;
*(bool*)ptr = true;
pthread_exit(NULL);
}
void* output(void* ptr)
{
cout << "Hello World" << endl;
for(long int x = 0; x < 1000000000; ++x) { }
*(bool*)ptr = true;
pthread_exit(NULL);
}
int main()
{
bool input_done = true;
bool output_done = true;
while (true)
{
pthread_t t1, t2;
if (input_done)
{
pthread_create(&t1, NULL, input, (void*)&input_done);
input_done = false;
}
if (output_done)
{
pthread_create(&t2, NULL, output, (void*)&output_done);
output_done = false;
}
}
}
是的,全局變量不是很好,但並非總是如此。 在我看來,您想要兩個線程一個將讀取輸入,另一個將寫入您的輸入,為此,您需要一個可以由兩個線程共享的全局變量,以便輸入線程可以在全局變量和輸出線程中寫入數據可以從全局變量讀取數據。 在這里,您需要同步兩個線程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.