尝试感受 C 中的 pthreads 和多线程编程。感谢这个网站,我设法获得了库链接,这样它就不再给我编译错误。
我试图让 2 个线程运行,一个打印 1000000 个 x,一个打印 1000000 个 o。
但是,运行程序时出现问题。命令行弹出一毫秒然后死掉,似乎什么也没有发生。甚至没有任何编译错误或任何我可以修复的错误。如果我注释掉线程创建和线程连接语句,则会弹出命令行并等待由于系统(“PAUSE”)而被击中的键。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include <pthread.h>
void* printChar(void *c);
int main(int argc, char *argv[])
{
pthread_t thread1;
pthread_t thread2;
pthread_create(&thread1,NULL,printChar,"x");
pthread_create(&thread2,NULL,printChar,"o");
pthread_join(thread1,NULL);
system("PAUSE");
return 0;
}
void* printChar(void *c)
{
char *str;
str = (char*)c;
int i;
for(i = 0; i < 1000000; i++)
{
printf("%c",str);
}
}
我正在从 Bloodshed Dev-C++ IDE 运行 DOS C 应用程序。我的 pthread .dll 和 .a 文件版本是:libpthreadGC2.a 和 pthreadGC2.dll
如果您需要让我知道的任何其他规范
提前致谢!
最佳答案
看看您的 printf:格式“%c”期望类型“int”,但参数 2 的类型为“char *”。所以应该是 printf("%s",str);
关于c - 在 Dev-C++ 中使用 pthreads - 奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6075283/