warning: format ‘%u’ expects type ‘unsigned int’, but argument 2 has type ‘pthread_t’
时间: 2024-02-07 18:03:40 浏览: 31
这个警告是因为使用了错误的格式说明符。在使用 printf() 函数输出 pthread_t 类型的变量时,应该使用 %lu 格式说明符,而不是 %u。因此,将代码中的 printf() 函数中的 %u 替换为 %lu 即可解决该警告。修改后的代码如下:
```c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
void *func1() {
printf("i am a thread, threadId: %lu\n", pthread_self());
}
int main(int argc, char *argv[]) {
int pid1, pid2, pid3;
pthread_t tid1, tid2, tid3, tid4, tid5, tid6, tid7, tid8;
pid1 = fork();
switch (pid1) {
case 0:
pid2 = fork();
switch (pid2) {
case 0:
printf("i am a process, pid: %d\n", getpid());
pthread_create(&tid1, NULL, func1, NULL);
pthread_create(&tid2, NULL, func1, NULL);
break;
default:
printf("i am a process, pid: %d\n", getpid());
pthread_create(&tid3, NULL, func1, NULL);
pthread_create(&tid4, NULL, func1, NULL);
// exit(0);
break;
}
default:
pid3 = fork();
switch (pid3) {
case 0:
printf("i am a process, pid: %d\n", getpid());
pthread_create(&tid5, NULL, func1, NULL);
pthread_create(&tid6, NULL, func1, NULL);
break;
default:
printf("i am a process, pid: %d\n", getpid());
pthread_create(&tid7, NULL, func1, NULL);
pthread_create(&tid8, NULL, func1, NULL);
// exit(0);
break;
}
}
return 0;
}
```
需要注意的是,pthread_t 类型的变量本质上是无符号长整型(unsigned long),因此使用 %lu 格式说明符可以保证输出正确。