#include <stdio.h>
#include <thread>
#include <map>
#include <mutex>
typedef struct VnoSInfo_
{
void* p = NULL;
int fun()
{
printf("fun ........ \n");
std::this_thread::sleep_for(std::chrono::milliseconds(10));
return 0;
}
}VnoSInfo;
int64_t getCurrentTicket()
{
return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
}
std::mutex g_mutex;
std::map<long, std::shared_ptr<VnoSInfo>> g_map;
long g_handle = 0;
bool g_isExit = false;
std::shared_ptr<VnoSInfo> GetSharePtr(long handle, bool isErase)
{
std::shared_ptr<VnoSInfo> p;
{
std::unique_lock<std::mutex> lock(g_mutex);
std::map<long, std::shared_ptr<VnoSInfo>>::iterator it = g_map.find(handle);
if (it != g_map.end())
{
p = it->second;
if (isErase)
{
g_map.erase(it);
}
}
}
return p;
}
long Create()
{
std::shared_ptr<VnoSInfo> p = std::make_shared<VnoSInfo>();
std::unique_lock<std::mutex> lock(g_mutex);
g_handle++;
g_map[g_handle] = p;
return g_handle;
}
int Destroy(long handle)
{
int ret = 0;
std::shared_ptr<VnoSInfo> p = GetSharePtr(handle, true);
if (p)
{
while (1)
{
printf("Destroy 222 p.use_count:%d time:%lld \n", p.use_count(), getCurrentTicket());
if (p.use_count() == 1)
{
p.reset();
printf("Destroy 333 p.use_count:%d time:%lld \n", p.use_count(), getCurrentTicket());
ret = 0;
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
else
{
ret = -1;
}
return ret;
}
int Incoming(long handle, char* data, int len)
{
std::shared_ptr<VnoSInfo> p = GetSharePtr(handle, false);
if (!p)
{
printf("Incoming error \n");
return -1;
}
return p->fun();
}
void ThreadRun(long t_handle)
{
while (!g_isExit)
{
if (t_handle > 0)
{
Incoming(t_handle, NULL, 10);
}
}
}
int main(int argc, char* argv[])
{
long t_handle = Create();
std::thread *m_Thread = new std::thread(ThreadRun, t_handle);
getchar();
int ret = Destroy(t_handle);
printf("Destroy ret:%d \n", ret);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
ret = Destroy(t_handle);
printf("Destroy 111 ret:%d \n", ret);
g_isExit = true;
m_Thread->join();
delete m_Thread;
m_Thread = 0;
return 0;
}
c++多线程安全同步释放示例
于 2024-04-16 19:54:19 首次发布