C++中使用pthread.h头文件报错 - 无法解析的外部符号 __imp__pthread_create,该符号在函数 _main 中被引用

C++ 中使用pthread.h头文件的方法
下载 pthreads-w32-2-7-0-release.exe, 链接: https://pan.baidu.com/s/137XgDd2cr2qii3Phli7u2Q 提取码: yx55

下载后运行会解压生成三个文件夹 Pre-built.2、pthreads.2、QueueUserAPCEx

打开Pre-built.2文件夹,分别复制include文件夹和lib文件夹中的文件到
VS安装目录下的\VC\include文件夹和\VC\lib文件夹中 或者
VC6.0安装目录下的\VC98\include文件夹和\VC 98\lib文件夹中

包含头文件pthread.h后,运行可能会提示错误
错误 1 error LNK2019: 无法解析的外部符号 __imp__pthread_create,该符号在函数 _main 中被引用
此时需要在代码中加入

#pragma comment(lib, "pthreadVC2.lib")

运行即可通过。
pthread.h头文件简单使用:

#include <iostream>
#include <pthread.h>
using namespace std;
#pragma comment(lib, "pthreadVC2.lib")

void * thread(void * a)
{
	for (int i = 0; i < 30; i++)
	{
		printf("线程执行第 %d 次\n", i+1);
	}
	return NULL;
}

void main()
{
	pthread_t id;
	int ret = pthread_create(&id,NULL, thread, NULL);
	if (ret != 0)
	{
		cout << "线程创建错误!" << endl;
		exit(-1);
	}
	for (int i = 0; i < 30; i++)
	{
		printf("main函数执行第 %d 次\n", i+1);
	}
	pthread_join(id, NULL);
}
要保证开启的线程能正常运行,需要注意以下几点: 1. 确保线程所需要的参数传递正确,可以使用结构体传递参数,或者使用全局变量来传递参数。 2. 线程函数所需要的资源必须先于线程创建而分配好,并且在线程结束后及时释放,避免资源泄漏。 3. 确保线程函数的执行不会与主线程产生竞争条件,例如在子线程访问共享数据时,应该使用互斥锁,避免数据的不一致性。 4. 在开启线程之前,应该先设置线程的属性,例如线程的优先级、调度策略等,确保线程能够按照预期的方式运行。 以下是一个示例程序,用于说明如何在 for 循环给另一个函数开启线程: ``` #include <pthread.h> #include <stdio.h> void *thread_func(void *arg) { int *num = (int *)arg; printf("Thread %d is running\n", *num); pthread_exit(NULL); } int main() { pthread_t thread_id; int i, num[5]; for (i = 0; i < 5; i++) { num[i] = i; if (pthread_create(&thread_id, NULL, thread_func, &num[i]) != 0) { printf("Error creating thread\n"); return 1; } printf("Thread %d created\n", i); } pthread_exit(NULL); return 0; } ``` 在上面的示例程序,我们使用了 pthread_create 函数来创建线程,该函数的第一个参数是线程标识符,第二个参数是线程的属性,第三个参数是线程函数的名称,第四个参数是传递给线程函数的参数。我们在 for 循环创建了 5 个线程,分别打印出了线程的编号。注意,我们在传递参数时使用了指针,确保了线程函数能够正确地取得参数。同时,我们也没有忘记在程序结束时调用 pthread_exit 函数,确保所有线程都能够正确地退出。
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值