程序应该从命令行获取参数,并通过posix线程添加参数。但Xcode成功构建它,但没有输出。这段代码有问题吗? 感谢
#include <iostream>
#include <pthread.h>
using namespace std;
void *Add(void *threadid){
long tid;
tid =(long)threadid;
long sum=0;
sum=sum+tid;
printf("%ld.\n",sum);
pthread_exit(NULL);
}
void *Print(void *threadid){
long tid;
tid =(long)threadid;
printf("%ld.\n",tid);
pthread_exit(NULL);
}
int main (int argc, char const *argv[])
{
if(argc<6){
printf("you need more arguments");
return -1;
}
long real[5];
pthread_t athread,bthread;
for (int x=1;x<=5;x++)
real[x-1]=atol(argv[x]);
for(int y=1;y<=5;y++)
pthread_create(athread[y],NULL,Add,(void *)&real[y]);
for(int y=1;y<=5;y++)
pthread_create(bthread[y],NULL,Print,(void *)&real[y]);
pthread_exit(NULL);
return 0;
}
答案 0 :(得分:1)
首先,我认为你应该检查pthread_create方法是否成功。 我在Apple下的pthread中没有经验,但基于该代码,我认为你在创建线程时遇到了问题。
答案 1 :(得分:1)
首先,printf
定义stdio.h
而不是iostream
。如果您想使用iostream
的C ++方式,则应使用cout << "Blabla " << var << endl;
代替。
其次,您使用错误的参数调用pthread_create
。由于定义athread
和bthread
不是数组,但您可以使用它们。我不完全确定为什么这甚至会编译,因为pthread_create
期望pthread_t*
作为第一个参数而你提供*pthread_t
。如果代码编译,它很可能会在运行时崩溃。
第三,您没有加入加法器线程。这意味着您的打印线程可以在加法器线程完成之前启动。
第四,你总结为局部变量。你应该总结成全球性的。不要忘记通过互斥或其他方式保护对它的访问。
第五,线程例程的参数是错误的。您正在传递指向值的指针而不是值本身,稍后将指针重新解释为值本身。您很可能希望使用(void *)real[y]
而不是(void *)&real[y]
。请注意,将long
投射到void *
并不适用于所有系统。在Mac OS X上,long
和void *
的长度相同(32或64位),但一般情况下都不是这样。
已编辑:您的代码甚至无法在OS X上编译:
$ g++ -o t.x t.cpp
t.cpp: In function ‘int main(int, const char**)’:
t.cpp:37: error: cannot convert ‘_opaque_pthread_t’ to ‘_opaque_pthread_t**’ for argument ‘1’ to ‘int pthread_create(_opaque_pthread_t**, const pthread_attr_t*, void* (*)(void*), void*)’
t.cpp:40: error: cannot convert ‘_opaque_pthread_t’ to ‘_opaque_pthread_t**’ for argument ‘1’ to ‘int pthread_create(_opaque_pthread_t**, const pthread_attr_t*, void* (*)(void*), void*)’
$ clang -o t.x t.cpp
t.cpp:37:5: error: no matching function for call to 'pthread_create'
pthread_create(athread[y],NULL,Add,(void *)&real[y]);
^~~~~~~~~~~~~~
/usr/include/pthread.h:304:11: note: candidate function not viable: no known
conversion from 'struct _opaque_pthread_t' to 'pthread_t *' (aka
'_opaque_pthread_t **') for 1st argument;
int pthread_create(pthread_t * __restrict,
^
t.cpp:40:5: error: no matching function for call to 'pthread_create'
pthread_create(bthread[y],NULL,Print,(void *)&real[y]);
^~~~~~~~~~~~~~
/usr/include/pthread.h:304:11: note: candidate function not viable: no known
conversion from 'struct _opaque_pthread_t' to 'pthread_t *' (aka
'_opaque_pthread_t **') for 1st argument;
int pthread_create(pthread_t * __restrict,
^
2 errors generated.
您是否甚至没有看到XCode提供的错误消息?