# std::thread

`thread` std lib allows us to spawn threads in cpp on demand, `join()` them or `detach()` them as per the requirement.

Thread execution is started as soon as it is created with as task.

```cpp
#include <iostream>
#include <thread>
#include <chrono>
#include <algorithm>
using namespace std;
using namespace std::chrono;
typedef long long int ull;

void findEven(ull start, ull end, ull *EvenSum)
{
    for (ull i = start; i <= end; ++i)
    {
        if (!(i & 1))
        {
            *(EvenSum) += i;
        }
    }
}

void findOdd(ull start, ull end, ull *OddSum)
{
    for (ull i = start; i <= end; ++i)
    {
        if (i & 1)
        {
            (*OddSum) += i;
        }
    }
}

int main()
{
    ull start = 0, end = 1900000000;

    ull OddSum = 0;
    ull EvenSum = 0;

    auto startTime = high_resolution_clock::now();

    // // WITH THREAD
    std::thread t1(findEven, start, end, &(EvenSum));
    std::thread t2(findOdd, start, end, &(OddSum));

    t1.join();
    t2.join();

    // // WITHOUT THREAD
    // findEven(start,end, &EvenSum);
    // findOdd(start, end, &OddSum);
    auto stopTime = high_resolution_clock::now();
    auto duration = duration_cast<microseconds>(stopTime - startTime);

    cout << "OddSum : " << OddSum << endl;
    cout << "EvenSum : " << EvenSum << endl;

    cout << "Sec: " << duration.count() / 1000000 << endl;

    return 0;
}
```

> Try this here.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://notes.tejpratapsingh.com/_/cpp/thread/threading/std-thread.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
