备注void *,最好添加返回值
原因:在实践中,虽然你的函数可能不需要返回任何值,但为了与 pthread_create 函数的预期函数指针格式相匹配,最好遵守函数指针所需的返回类型。这是一种良好的编程实践,确保你的代码能够在各种情况下正确编译和执行。即使编译器没有强制要求函数按照格式返回值,也建议遵循函数指针的声明,以防止未来的问题或兼容性问题。文章来源地址https://www.toymoban.com/news/detail-734611.html
#include <stdio.h>
#include <pthread.h>
void *ReadfileThreadFunc(void *arg) {
const char *filename = (const char *)arg;
FILE *file = fopen(filename, "r");
if (file != NULL) {
char buffer[256];
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("%s", buffer); // 输出文件内容到控制台
}
fclose(file);
} else {
printf("Failed to open the file.\n");
}
return NULL;
}
int main() {
pthread_t MyThread;
const char *filename = "example.txt";
// 创建线程,并传递文件名作为参数
if (pthread_create(&MyThread, NULL, ReadfileThreadFunc, (void *)filename) != 0) {
printf("Failed to create thread.\n");
return 1;
}
// 等待新线程结束
if (pthread_join(MyThread, NULL) != 0) {
printf("Failed to join thread.\n");
return 1;
}
return 0;
}
文章来源:https://www.toymoban.com/news/detail-734611.html
到了这里,关于C语言 pthread_create的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!