c - 我如何在 C 中为 Windows 创建多线程?

标签 c multithreading winapi timer

我不知道如何在 C 中创建线程,我看到了一篇关于 pthread.h 库的评论,但后来我听说它只适用于 Linux 操作系统,我有一个定时器功能,我想创建一个线程这个函数,但我不知道我需要使用的库和编写代码的语法,如果有人可以为我提供一个简单的线程代码,或者告诉我我需要放什么东西和函数的参数。

这是我在用户申请的特定时间创建倒计时的功能: 我需要用那个函数创建一个线程。

函数(倒计时):

#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

void countdown(int second)
{
    int secs = 1;
    time_t unix;
    struct tm * timeinfo;
    time(&unix);
    timeinfo = localtime(&unix);
    int t1 = timeinfo->tm_sec;
    int t2 = timeinfo->tm_sec;
    int i = 0;

    while(1 == 1)
    {
       time(&unix);
       timeinfo = localtime(&unix);
       if((t1 + i)  == timeinfo->tm_sec)
       {
              system("cls");
              printf("Time left %d\n", timeinfo->tm_sec - t2 - second);
              i++;
       }
       if(timeinfo->tm_sec >= (t1 + second))
       {
           system("cls");
           puts("Your time its done");
           break;
       }

    }
}

int main()
{
    int limit;
    printf("How much time would you like (In secs): ");
    scanf("%d", &limit);
    countdown(limit);

    system("PAUSE");
    return 0;
}

最佳答案

这是winapi线程的简单指南
http://www.cs.rpi.edu/academics/courses/netprog/WindowsThreads.html

也就是说,C 是一种极简语言,没有像 java 那样的内置线程(也没有庞大的额外库)。它是一种建立在它之上的通用语言。在类 Unix 系统上,存在超出 ANSI/ISO 标准的系统范围标准 c 库,它们是 posix 标准的一部分,pthreads 是 posix-threads。 Windows C 库是 MS 以自己的方式制作的。您可以使用提供多操作系统支持的框架,如 glib 或 qt(Windows、Linux、其他 *nix)。还有一些端口和兼容层可以在 Windows 中使用 posix 设施。 Cigwin 为您提供除了库之外的完整 posix 环境,MinGW 编译器允许您在 win32 层之上使用 posix 函数的端口。

像 glib 和 qt 这样的框架最适合让你的代码保持多平台,它们隐藏了操作系统的细节,允许更通用的方法。

glib 是用于 GUI 开发的 GTK 库的一部分,QT 也是一个 GUI 开发框架,但使用 C++。

关于c - 我如何在 C 中为 Windows 创建多线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8446757/

相关文章:

c - 在线程内创建变量和传递指针的问题

c++ - 在同一链中执行异步操作

C# 查询进程所有者 (Windows 7 x64)

c++ - 基于对话框的 MFC 应用程序的应用程序范围的周期性任务

c - (struct)的大小是多少?

java - 如何在 C/C++ 中执行无符号右移(Java 中的 >>>)?

c# - 调试期间的线程

c# - 使用 SendMessage 拖放

C lang - 当应用于负 int 时,sprintf 创建 8 个字符长的字符串而不是 6 个

c++ - 使用位域转换大型项目以使用更便携的东西