我将启动一个将使用多线程的C编程项目。在我开始这个项目之前,我已经编写了一个练习代码。我的目的是了解互斥和线程的工作原理。但它无法正常工作。这是代码:
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
pthread_mutex_t myMutex;
char myStrings[100][30];
int i=0;
void *PrintThread1()
{
printf("this is initial of FIRST Thread\n");
for (int j=0; j<33; j++) {
pthread_mutex_lock(&myMutex);
strcpy(myStrings[i], "This is FIRST thread");
i++;
pthread_mutex_unlock(&myMutex);
}
pthread_exit(NULL);
}
void *PrintThread2()
{
printf("this is initial of SECOND Thread\n");
for (int j=0; j<33; j++) {
pthread_mutex_lock(&myMutex);
strcpy(myStrings[i], "This is SECOND thread");
i++;
pthread_mutex_unlock(&myMutex);
}
pthread_exit(NULL);
}
void *PrintThread3()
{
printf("this is initial of THIRD Thread\n");
for (int j=0; j<33; j++) {
pthread_mutex_lock(&myMutex);
strcpy(myStrings[i], "This is THIRD thread");
i++;
pthread_mutex_unlock(&myMutex);
}
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
pthread_t firstThread, secondThread, thirdThread;
//pthread_attr_t attr;
pthread_mutex_init(&myMutex, NULL);
//pthread_attr_init(&attr);
//pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
int ft;
ft = pthread_create(&firstThread, NULL, PrintThread1(), NULL);
if (ft){
printf("ERROR; return code from pthread_create() is %d\n", ft);
exit(-1);
}
ft = pthread_create(&secondThread, NULL, PrintThread2(), NULL);
if (ft){
printf("ERROR; return code from pthread_create() is %d\n", ft);
exit(-1);
}
ft = pthread_create(&thirdThread, NULL, PrintThread3(), NULL);
if (ft){
printf("ERROR; return code from pthread_create() is %d\n", ft);
exit(-1);
}
pthread_join(firstThread, NULL);
pthread_join(secondThread, NULL);
pthread_join(thirdThread, NULL);
pthread_mutex_destroy(&myMutex);
for (int j=0;j<100; j++) {
printf("String[%d] = %s\n",j,myStrings[j]);
}
printf("\n");
pthread_exit(NULL);
return -1;
}
当我执行此代码时,我的结果是:
this is initial of FIRST Thread
Program ended with exit code: 0
我无法弄清楚错误。
答案 0 :(得分:1)
ft = pthread_create(&firstThread, NULL, PrintThread1(), NULL);
应该阅读
ft = pthread_create(&firstThread, NULL, PrintThread1, NULL);
同样适用于所有pthread_create
次来电。
要使用pthread_create
,你需要传递一个线程启动例程的地址,你在C中通过写一个函数名称而不用函数调用括号来做它
正如您所写的那样,您调用预期的线程启动例程,主线程上的 ,并传递返回的任何内容pthread_create
是线程启动例程。但它永远不会返回,因为它调用pthread_exit
,因为pthread_create
尚未被调用,所以只有一个线程)终止整个程序。
不幸的是,你必须在编译器捕获这个错误之前发出 way 的警告,即便如此,问题仍然不是很清楚:
$ gcc -std=c99 -Wall -pedantic -pthread test.c
test.c: In function ‘main’:
test.c:60:45: warning: ISO C forbids passing argument 3
of ‘pthread_create’ between function pointer and ‘void *’ [-Wpedantic]
ft = pthread_create(&firstThread, NULL, PrintThread1(), NULL);
^
没有-pedantic
,没有投诉。