64,654
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <thread>
void function ()
{
std::cout << std::this_thread::get_id() << std::endl;
}
int main ()
{
std::thread t(function);
std::thread t2(function);
std::thread t3(function);
t .join();
t2.join();
t3.join();
}
试了一下没问题,输出比如:
140526880892672
140526872499968
140526864107264
可以看到三个不同的线程,你试试在你哪里一样吗。
另外,std::thread::id 应该用 std::cout 输出,printf 很可能给搞错。#include <thread>
#include "win32_sem.h"
uint32_t sem = create_semaphore(0, INT32_MAX);
void process_packet()
{
printf("thread :%d begin process data. \n", std::this_thread::get_id());
for (uint64_t i = 0; i < UINT64_MAX; ++i);
printf("thread: %d process data over. \n", std::this_thread::get_id());
}
void extract_packet()
{
while (true)
{
printf("thread:%d - %d wait data coming ... \n", std::this_thread::get_id(), ::GetCurrentThreadId());
wait_semaphore(sem, INFINITE);
printf("thread:%d - %d receive data. \n", std::this_thread::get_id(), ::GetCurrentThreadId());
// get data from array
process_packet();
}
}
void test_cpp_thread()
{
std::thread t(extract_packet);
t.detach();
std::thread t2(extract_packet);
t2.detach();
std::thread t3(extract_packet);
t3.detach();
release_semaphore(sem, 3);
std::this_thread::sleep_for(std::chrono::seconds(5));
release_semaphore(sem, 1);
std::this_thread::sleep_for(std::chrono::seconds(5));
release_semaphore(sem, 1);
}
int main()
{
test_cpp_thread();
system("pause");
return 0;
}