Unique id inside of thread

Flaviu_ 1,031 Reputation points
2022-04-05T14:35:30.493+00:00

It's the following approach assure me a unique id in every thread ?

class CMyDoc : public CDocument
{
 static size_t m_id;
.....

};

then

size_t CMyDoc::m_id = 1;

And I have a method which is called as:

std::vector<std::thread> v;
for (int x = 0; x < 5; ++x)
{
  v.push_back(std::thread(ExecutionThread, AfxGetMainWnd(), _T("bla bla"));
}

the thread method is:

void CMyDoc::ExecutionThread(HWND hWndPostMessage, const CString& sFile)
{
 const size_t id{ m_id++ };
....
        ::PostMessage(hWndPostMessage, WMU_NOTIFYTHREAD, 0, static_cast<LPARAM>(id));
}

My question is: id from CMyDoc::ExecutionThread is unique across all threads ?

Developer technologies | C++
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2022-04-05T14:53:07.05+00:00

    According to https://www.bing.com/search?q=is+intel+increment+atomic%3F, it is necessary to use the std::atomic_size_t for m_id. (Or use the LONG volatile type, and the InterlockedIncrement function instead of ++; however, it performs ++m_id instead of m_id++).

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. RLWA32 49,636 Reputation points
    2022-04-05T15:02:00.057+00:00

    This function is specifically designed to return a unique ID for the calling thread nf-combaseapi-cogetcurrentprocess

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.