如何消除这段代码中的全局变量?
下面的代码创建两个线程。一个用于接受输入,另一个用于同时打印文本。根据我所读到的有关该主题的内容,全局变量在传统的 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;
}
}
}
The below code creates two threads. One to accept input and another to print out text simultaneously. From what I've read on the topic, global variables are considered bad form in traditional c++ code. Yet I cannot think of a way to make the input/output simultaneous without them.
How can I eliminate these two boolean global variables from my code?
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;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有一些指针传递给您不使用的线程函数。将指针传递给变量并通过这些指针访问它们,然后您就可以在函数
main
或其他任何地方在堆栈上分配变量。因此,例如您的
output
函数将类似于pthread_create
调用:There are pointers passed to your thread functions which you don't use. Pass pointers to your variables and access them through these pointers, then you'd be able to allocate variables on stack in function
main
or wherever else.So, for example your
output
function will look likeand
pthread_create
call:在
main
中创建input_done
和output_done
局部变量,通过使用pthread_create,并让线程函数通过它们接收到的指针修改它们。
示例(根据样式调整):
Make
input_done
andoutput_done
local variables inmain
, pass pointers to them to the thread functions by using the fourth parameter topthread_create
, and let the thread functions modify them through the pointers they receive.Example (adjusted for style):
是的,全局变量不好,但并非总是如此。在我看来,你想要两个线程,一个将读取输入,另一个将写入你的输入,为此你需要一些可以由两个线程共享的全局变量,以便输入线程可以在全局变量和输出线程中写入数据可以从全局变量中读取数据。这里需要同步两个线程。
Yes, global variables are not good but not always. It seems to me that you want two threads one will read the input and other will write your input, for this you need some global variable that can be shared by both the thread, so that input thread can write data in global variable and output thread can read data from global variable. Here you need to synchronize both threads.