Horje
c++ threads Code Example
c++ create threads
#include <thread>
void foo() 
{
  // do stuff...
}
int main() 
{
  std::thread first (foo);
  first.join();
}
c++ threads
#include <iostream>
#include <thread>
#include <chrono>

void task1() {

    /* count from 1 to 10 with 1 second pause in between */
    for(int i = 1; i <= 10; ++i) {

        /* simulating a length process, sleeping for 1 second */
        std::this_thread::sleep_for(std::chrono::seconds(1));

        std::cout << "TASK 1: " << i << std::endl;

    }

}

void task2() {

    /* count from 1 to 10 with 2 seconds pause in between */
    for(int i = 1; i <= 10; ++i) {

        /* simulating a length process, sleeping for 2 seconds */
        std::this_thread::sleep_for(std::chrono::seconds(2));

        std::cout << "TASK 2: " << i << std::endl;

    }

}

int main(int count, char* args[]) {

    /* start task 1 from a different thread */
    std::thread t1{task1};

    /* start task 2 from a different thread */
    std::thread t2{task2};

    /* wait for task1 and task2 to finish running */
    t1.join();
    t2.join();

    return 0;

}




Cpp

Related
conditional operator in c++ Code Example conditional operator in c++ Code Example
c++ compile to exe command line Code Example c++ compile to exe command line Code Example
print duplicate characters from string in c++ Code Example print duplicate characters from string in c++ Code Example
c++ rand include Code Example c++ rand include Code Example
c++ in cmd Code Example c++ in cmd Code Example

Type:
Code Example
Category:
Coding
Sub Category:
Code Example
Uploaded by:
Admin
Views:
9