Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C11 threads on Windows

I'm creating cross platform software in Visual Studio 2012 express on Windows. For obvious reasons I can't use .NET's System::Threading::Thread. I was hoping I could use the new threading features of C11 (threads.h, not pthread.h), while using VS2012 since the I created a abstract framework based on .NET forms. I'm starting to believe that it's impossible for Windows. Does someone have an idea. I'll only use C++ libraries (boost and std) if those are my only options.

Is there someone who knows what to do?

like image 740
JMRC Avatar asked Feb 28 '13 17:02

JMRC


People also ask

Does STD thread work in Windows?

std::thread is part of the (new) standard, and is portable. Unless you're only targeting Windows AND you need to interact with your threads using the WinAPI, std::thread is the way to go.

Does MSVC support C11?

All the required features of C11 and C17 are supported. This meant adding the following functionalities: _Pragma.

What are Windows threads?

A thread is the basic unit to which the operating system allocates processor time. A thread can execute any part of the process code, including parts currently being executed by another thread. A job object allows groups of processes to be managed as a unit.

Is Windows multi threaded?

Windows is a preemptive multithreading operating system which manages threads. Each program is assigned a single thread of execution by default.


2 Answers

Visual Studio 2012 doesn't support C11's threading (Microsoft has stated repeatedly that it has little interest in keeping current with C, preferring to focus on C++), but it does support C++11's std::thread and related facilities. If you're writing C++, you should arguably be using them anyways instead of C's threading libraries.

like image 70
Matt Kline Avatar answered Sep 29 '22 08:09

Matt Kline


Visual Studio 2017 contains a header xthreads.h which is very similar but slightly different fromthreads.h. For example:

from 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)}));
}

Would be

#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)}));
}

* NOTE: xthreads.h IS NOT standard and therefore subject to change. *

There is also an emulation library at https://gist.github.com/yohhoy/2223710 .

like image 34
annoying_squid Avatar answered Sep 29 '22 09:09

annoying_squid