-1

I am trying to use threading in an if statement.

The following code gives an error saying t1 in t1.join is not declared in this scope. Is there a way to make the loop skip the first thread operation and start multithreading for the other passes?

  #include <thread>
  void someFunction() {/*someTask*/}

 void main() {
     bool isFirstRun = true;
     while(true){

     if(isFirstRun==false){std::thread t1(someFunction);}

     //some long task

     if(isFirstRun==false){t1.join}
     if(isFirstRun){isFirstRun = false;}
     }
 }

More generally, is there a way to create a thread like a global variable in C++ and control its execution anywhere in the code? I saw the following in java and thought this might solve my problem if implemented in C++:

Thread t1 = new Thread(new EventThread("e1")); 
//some tasks here
t1.start(); 
//some tasks here
t1.join();
ozgeneral
  • 6,079
  • 2
  • 30
  • 45

1 Answers1

2
if(isFirstRun==false){std::thread t1(someFunction);}

The scope of t1 is limited to the block following the first if statement—the curly braces in the statement quoted above. It subsequently goes out of scope and is therefore not accessible later in the function.

If you want it to remain in scope, define it outside of an if block, perhaps at the scope of your main() function.

I saw the following in java and thought this might solve my problem if implemented in C++:

Thread t1 = new Thread(new EventThread("e1")); 

Certainly you can new up an object (new returns a pointer), but C++ isn't Java. You should not follow the same programming patterns. If creating the object on the stack is sufficient, then do that.

void main()

Also, there is no such function as void main() in C++; the entry point returns int.


A simple example of implementing threading in C++ is available here.

Community
  • 1
  • 1
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • do you mean I should do `if(firstRun){/*without threading*/}else{/*same code with threading*/}` – ozgeneral Mar 05 '16 at 15:37
  • You know how you defined the `isFirstRun` variable at the beginning of the `main()` function? You can do the exact same thing with `t1`. – Cody Gray - on strike Mar 05 '16 at 15:38
  • Yeah but it starts running immediately then. I want it to start running in while loop, after the first run. – ozgeneral Mar 05 '16 at 15:39
  • Well, you can declare the variable at an outer scope (`std::thread t1;`) so that it will be default-constructed, which doesn't start a thread. Then, when you want to start the thread, you can create a new thread and assign it to `t1`: `t1 = std::thread(...);` – Cody Gray - on strike Mar 05 '16 at 15:43
  • That was what I was looking for, thanks. – ozgeneral Mar 05 '16 at 15:44