开发者

Threaded C programs in minGW

I am creating a program that intercepts all packets when a certain link is down. I would need to implement the sniffer and the link-checker as threads. But minGW does not have pthreads.

How do you implement threads in minGW?

Edit:开发者_如何学Canswer

http://www.codeproject.com/KB/threads/sync.aspx

Vivek Goel led me to this (_beginthread). Both examples compile on Code::blocks/minGW!


MinGW doesn't provide a full POSIX model. If you want threads in the standard package, you'll have to use the Windows variety.

It states on the MinGW main page:

MinGW compilers provide access to the functionality of the Microsoft C runtime and some language-specific runtimes. MinGW, being Minimalist, does not, and never will, attempt to provide a POSIX runtime environment for POSIX application deployment on MS-Windows. If you want POSIX application deployment on this platform, please consider Cygwin instead.

Cygwin does have pthreads support because it provides the Cygwin DLL, an emulation layer, whereas MinGW is more gcc for use with the Windows way of doing things.

Alternatively, if Cygwin isn't an option, you can look into Pthreads/Win32 which claims to work with MinGW.


With MinGW you have some options. My recomendations:

  1. Use native Windows API to make your threads.

  2. Use a good library to manage that. I usually use a C++ framework called JUCE to have a better life.

Using Windows API you could try something like this:

/*
 *  main.c
 *
 *  Created on: 18/10/2011
 *  Author: Cesar Carlos Ortiz Pantoja.
 */

#include <windows.h>
#include <stdio.h>

int exitCondition;

struct threadParams{
    int param1;
    int param2;
};

static DWORD WINAPI myFirstThread(void* threadParams)
{
    struct threadParams* params = (struct threadParams*)threadParams;

    while(exitCondition){
        printf("My Thread! Param1:%d, Param2:%d\n", params->param1, params->param2);
        fflush(stdout);
        Sleep(1000);
    }

    return 0;
}

int main(void){
    DWORD threadDescriptor;
    struct threadParams params1 = {1, 2};
    exitCondition = 1;

    CreateThread(
        NULL,                   /* default security attributes.   */
        0,                      /* use default stack size.        */
        myFirstThread,          /* thread function name.          */
        (void*)&params1,        /* argument to thread function.   */
        0,                      /* use default creation flags.    */
        &threadDescriptor);     /* returns the thread identifier. */

    while(1){
        printf("Main Program!\n");
        fflush(stdout);
        Sleep(2000);
    }

    return 0;
}

Regards


You have to use WIN 32 Threads API see http://www.mingw.org/wiki/Use_the_thread_library http://msdn.microsoft.com/en-us/library/ms684254(v=vs.85).aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜