不可能以标准方式进行。您需要依赖一些第三方方法。即pthreads 或Win32 threads。
POSIX 示例:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void* print_once(void* pString)
{
printf("%s", (char*)pString);
return 0;
}
void* print_twice(void* pString)
{
printf("%s", (char*)pString);
printf("%s", (char*)pString);
return 0;
}
int main(void)
{
pthread_t thread1, thread2;
// make threads
pthread_create(&thread1, NULL, print_once, "Foo");
pthread_create(&thread2, NULL, print_twice, "Bar");
// wait for them to finish
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
Win32 示例:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
DWORD print_once(LPVOID pString)
{
printf("%s", (char*)pString);
return 0;
}
DWORD print_twice(LPVOID pString)
{
printf("%s", (char*)pString);
printf("%s", (char*)pString);
return 0;
}
int main(void)
{
HANDLE thread1, thread2;
// make threads
thread1 = CreateThread(NULL, 0, print_once, "Foo", 0, NULL);
thread2 = CreateThread(NULL, 0, print_once, "Bar", 0, NULL);
// wait for them to finish
WaitForSingleObject(thread1, INFINITE);
WaitForSingleObject(thread2, INFINITE);
return 0;
}
如果您想在两个平台上都使用 POSIX,可以使用 Windows 端口。