我正在学习Pthreads。我的代码按照我想要的方式执行,我可以使用它。但是它给了我关于编译的警告。
我使用编译:
gcc test.c -o test -pthread
与GCC 4.8.1。我收到了警告
test.c: In function ‘main’:
test.c:39:46: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
pthread_create(&(tid[i]), &attr, runner, (void *) i);
^
test.c: In function ‘runner’:
test.c:54:22: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
int threadnumber = (int) param;
^
以下代码出现此错误:
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#define MAX_THREADS 10
int sum; /* this data is shared by the thread(s) */
void *runner(void * param);
int main(int argc, char *argv[])
{
int num_threads, i;
pthread_t tid[MAX_THREADS]; /* the thread identifiers */
pthread_attr_t attr; /* set of thread attributes */
if (argc != 2) {
fprintf(stderr, "usage: test <integer value>\n");
exit(EXIT_FAILURE);
}
if (atoi(argv[1]) <= 0) {
fprintf(stderr,"%d must be > 0\n", atoi(argv[1]));
exit(EXIT_FAILURE);
}
if (atoi(argv[1]) > MAX_THREADS) {
fprintf(stderr,"%d must be <= %d\n", atoi(argv[1]), MAX_THREADS);
exit(EXIT_FAILURE);
}
num_threads = atoi(argv[1]);
printf("The number of threads is %d\n", num_threads);
/* get the default attributes */
pthread_attr_init(&attr);
/* create the threads */
for (i=0; i<num_threads; i++) {
pthread_create(&(tid[i]), &attr, runner, (void *) i);
printf("Creating thread number %d, tid=%lu \n", i, tid[i]);
}
/* now wait for the threads to exit */
for (i=0; i<num_threads; i++) {
pthread_join(tid[i],NULL);
}
return 0;
}
/* The thread will begin control in this function */
void *runner(void * param)
{
int i;
int threadnumber = (int) param;
for (i=0; i<1000; i++) printf("Thread number=%d, i=%d\n", threadnumber, i);
pthread_exit(0);
}
如何修复此警告?
答案 0 :(得分:45)
快速修复可能只会转发long
而不是int
。在许多系统上,sizeof(long) == sizeof(void *)
。
更好的想法可能是使用intptr_t
。
int threadnumber = (intptr_t) param;
和
pthread_create(&(tid[i]), &attr, runner, (void *)(intptr_t)i);
答案 1 :(得分:1)
pthread_create(&(tid[i]), &attr, runner, (void *) i);
您正在传递本地变量 i
作为runner
,sizeof(void*) == 8
和sizeof(int) == 4
(64位)的参数。
如果要传递i
,则应将其包装为指针或其他内容:
void *runner(void * param) {
int id = *((int*)param);
delete param;
}
int tid = new int; *tid = i;
pthread_create(&(tid[i]), &attr, runner, tid);
您可能只想要i
,在这种情况下,以下内容应该是安全的(但远非推荐):
void *runner(void * param) {
int id = (int)param;
}
pthread_create(&(tid[i]), &attr, runner, (void*)(unsigned long long)(i));
答案 2 :(得分:0)
我也得到了同样的警告。所以为了解决我的警告我将int转换为long然后这个警告就消失了。关于警告“从不同大小的整数转换为指针”,您可以保留此警告,因为指针可以保存任何变量的值,因为64x中的指针是64位而32x中的指针是32位。
答案 3 :(得分:-3)
尝试传递
#Code block A
import os
for i in dir(os):
print (help(os.i))