1

For instance take example of a program which calculates the time you take to type a paragraph and displays the time you took ( at the end ). Here our program is simultaneously performing two tasks : 1.Waiting for user to type ( taking input ). 2.A clock behind counts the time elapsed .

How can I accomplish both the tasks during execution ( at the same time ) . [ OK ! You may think of subtracting final & initial time which we may get by system but I want multitask to take place .]

I tried a lot searching for standard library functions but none of them do it . I think the only way to make multitask happen is smart algorithm of the program which does many tasks simultaneously as well as efficiently . Am I wrong ?

  • http://stackoverflow.com/questions/266168/simple-example-of-threading-in-c – wjmolina Mar 17 '14 at 14:16
  • 2
    Do you want a C answer or a C++ answer? The correct idiomatic answers are VERY different. – Fred Larson Mar 17 '14 at 14:16
  • 1
    It's fairly easy to do multitasking: First, decide if you're coding in `C` or `C++`. Second, choose `C++`. Third, read up on `std::thread`. – stefan Mar 17 '14 at 14:17
  • 2
    @stefan: Fourth, read an entire book (or maybe several) on concurrent programming to learn about all the issues of synchronization, communication, different threading techniques, etc. – Fred Larson Mar 17 '14 at 14:20
  • @FredLarson Oh yeah, I usually forget to do this step :D – stefan Mar 17 '14 at 14:24
  • 2
    @FredLarson: Fifth - start pulling your hair out if, even after all your best efforts, you still run into concurrency-related issues, as you inevitably will. – Elias Van Ootegem Mar 17 '14 at 14:32

2 Answers2

4

Probably multithreading. Use pthreads.

[Although, in your example it's not needed. Just

int time = getTime();
// run program
int endTime = getTime();
printf("%d\n", endTime - time);

]

djechlin
  • 59,258
  • 35
  • 162
  • 290
2

In C++11 you can use std::thread which is of course part of the standard.

This will not work if using C however or older c++ compilers.

An alternative is boost::thread

const_ref
  • 4,016
  • 3
  • 23
  • 38