章节目录:
前提条件
要启用测试多线程应用程序的功能,需在构建设置的编译器选项(如设置项目和文件选项中所述)中添加以下选项:
"-DCPPTEST_THREADS=1"
此选项将激活 C++test 的运行时库中的多线程支持,并禁用对线程相关例程使用安全桩函数
注意事项
- C++test 的测试可执行文件必须与适当的运行时库链接(即,用于 Visual C++ 编译器的 C 运行时库的多线程版本或 UNIX 上的 pthread 库)。
- C++test 的运行时不控制线程的生命周期——我们建议您编写测试用例时确保所有线程在测试用例完成时终止。
已知的问题和局限性
已知的问题和局限性:
- 如果启用了多线程支持(使用 -DCPPTEST_THREADS=1),但在链接时未使用适当的库(或混用了多线程和单线程的 C 运行时),测试可执行文件可能会生成错误的测试结果,或者意外终止。
- 非主线程中的意外行为(信号、未处理异常、超时)将导致测试可执行文件终止。
构建 C++test 运行时库
C++test 的默认运行时库内置了多线程应用程序测试支持。除非您要构建具有多线程支持的自定义运行时库(例如,用于嵌入式测试),否则无需执行其他操作。如果您需要使用多线程支持来构建自定义运行时库,请将 "- DCPPTEST_THREADS_ENABLED=1"
添加到编译器命令行。
支持的线程 API
运行时库的实现可以使用以下类型的线程 API:
- Windows 线程
- POSIX 线程
- VxWorks 6.x
使用其他线程 API
如果需要使用其他线程 API(或自定义的 API),则必须实现以下类型和例程。
注意,C++test 运行时源中的 CppTestThread.c 文件包含线程支持例程的定义;可以用作示例或更改的基础。
TIs - 线程本地存储
typedef IMPLEMENTATION_DEPENDENT_TYPE CppTestThreadKey; /** * Creates key for thread local storage data * Returns 0 on success */ extern int localThreadKeyCreate(CppTestThreadKey* key); /** * Deletes key for thread local storage data * Returns 0 on success */ extern int localThreadKeyDelete(CppTestThreadKey key); /** * Returns a thread specific value associate with a key */ extern void* localThreadGetSpecific(CppTestThreadKey key); /** * Associate a thread specific value with a key * Returns 0 on success */ extern int localThreadSetSpecific(CppTestThreadKey key, void* value);
互斥锁
注意:C++test 运行时假设互斥锁可以静态初始化。
typedef IMPLEMENTATION_DEPENDENT_TYPE CppTestThreadMutex; #define CPPTEST_THREADS_MUTEX_STATIC_INIT <IMPLEMENTATION_DEPENDENT_STATIC_INITIALIZER> /** * Initializes mutex * @return 0 on success */ extern int localThreadMutexInit(CppTestThreadMutex* mutex); /** * Destroy and release resources used by mutex * @return 0 on success */ extern int localThreadMutexDestroy(CppTestThreadMutex* mutex); /** * Lock mutext and return when calling thread becames is owner of it. * @return 0 on success */ extern int localThreadMutexLock(CppTestThreadMutex* mutex); /** * Releases mutex owned by calling thread. * @return 0 on success */ extern int localThreadMutexUnlock(CppTestThreadMutex* mutex);
杂项
/** * Exits calling thread * (never returns) */ extern void localThreadExit(); /** * @return non-zero if threads already finished execution */ extern int localThreadFinished(CppTestThread* thread); /** * @return non-zero if threads are supported in current build * (proper macros, libraries, compiler options were used). */ extern int localThreadsSupported(void); /** * Initializes given thread structure */ extern void localThreadInit(CppTestThread* thread);