multithreading

Feb 4, 2010 at 11:58am
hello.
was wondering, first of all, is using multithreading a "beginner" problem?
anyhow, i'm trying to run two pieces of code together.
one code displaying how many days have passed(1day=1sec)
while the other is asking for user input
(what would you like you build?
1.barn
2.farm
3... etc.
)

the point is that the days keep passing by, not waiting for the user input.
after googling a bit i found that this operation is called multithreading.
as i could not find any decent and understandable tutorial online, I'm turning to you, my saviours, to maybe shed some light on this matter, or direct me to a good resource that i can learn from.

Thanks in advance!
Feb 4, 2010 at 12:07pm
You can not use console to input and output concurrently.

Current standard of C++ doesn't care about multithreading(draft version of new one does).
But you can use third library like BOOST, TBB, OpenMP and others, or operating system specific functions.
link to TBB
http://www.opentbb.org
link to boost
http://www.boost.org
Last edited on Feb 4, 2010 at 12:07pm
Feb 4, 2010 at 12:13pm
i see..
that being said, can a window.h program can be used for input/output?
Feb 4, 2010 at 12:34pm
If you mean input/output using console then use <iostream>
Feb 4, 2010 at 12:49pm
naturally i meant outputting, for example, updated time every 3 seconds, while still waiting for the user to enter data.

So the program would look while running

loop this
{
<updated time here>

please enter the number(wait 0.0001 sec for user input, if no input, go back again to start)
}
Feb 4, 2010 at 1:54pm
What you want is multithreading, but undo Linux I could solve this problem using fork() (It's to create new process, not thread)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int secs = 0;

int main()
{
    pid_t pid = fork();
    if (pid == 0)
    {
         //work with user input
    }
    else
    {
         int i = 0x7ff; //days count
         while(i != 0)
         {
             if (i % 3 == 0)
             {
                   std::cout << "Days passed :" << i << '\n';
                   ++i;
              }
          }
    }
    wait(pid);
    return 0;
}
Last edited on Feb 4, 2010 at 1:55pm
Feb 4, 2010 at 2:04pm
Threading is typically not a beginner question. There are lots of things you need to know before using threads, mostly dealing with thread synchronization and the sharing of data.

Threading is one way to accomplish this. You can use asynchronous IO (see the Boost Asio library) to do this which uses threads in the background. Or you can use poll or select (I assume windows has an equivalent) to wait for a limited amount of time for user input.

Feb 4, 2010 at 7:01pm
Okay i guess i'll hit a softer topic first :)
sorry for the trouble, but i just don't understand most of it..
much appreciated :)
Topic archived. No new replies allowed.