Windows上的C11线程

C11 threads on Windows

本文关键字:线程 C11 上的 Windows      更新时间:2023-10-16

我正在Windows上创建Visual Studio 2012 express的跨平台软件。由于显而易见的原因,我不能使用。net的System::Threading::Thread。我希望我能使用C11 (threads.h,而不是pthread.h)的新线程功能,而使用VS2012,因为我创建了一个基于。net表单的抽象框架。我开始相信这对Windows来说是不可能的。有人有什么主意吗?我只会使用c++库(boost和std),如果它们是我唯一的选择。

有人知道该怎么做吗?

Visual Studio 2012不支持C11的线程(微软已经反复声明,它没有兴趣与C保持同步,更愿意专注于c++),但它确实支持c++ 11的std::线程和相关设施。如果你正在编写c++,你应该使用它们而不是C的线程库。

Visual Studio 2017包含一个标题xthreads.h,它与threads.h非常相似,但略有不同。例如:

从https://en.cppreference.com/w/c/thread/thrd_sleep

#include <threads.h>
#include <time.h>
#include <stdio.h>
int main(void)
{
    printf("Time: %s", ctime(&(time_t){time(NULL)}));
    thrd_sleep(&(struct timespec){.tv_sec=1}, NULL); // sleep 1 sec
    printf("Time: %s", ctime(&(time_t){time(NULL)}));
}

#include <thr/xthreads.h>
#include <time.h>
#include <stdio.h>
int main(void)
{
    struct xtime stoptime;
    xtime_get( &stoptime, 1);
    stoptime.sec += 1;
    printf("Time: %s", ctime(&(time_t){time(NULL)}));
    _Thrd_sleep( &stoptime ); 
    printf("Time: %s", ctime(&(time_t){time(NULL)}));
}

*注:xthreads.h不是标准,因此可能会发生变化。*

也有一个仿真库在https://gist.github.com/yohhoy/2223710 .

C11线程接口主要是从Dikumware专有线程库中的线程接口复制过来的。他们的东西在不同的平台上运行,他们创建了一个接口,作为Windows线程和POSIX线程功能的交集。

他们现在是否把它作为"官方的"C11线程库,我不知道,但应该离它不远了。