在板子生产完成后,需要对其进行测试,以验证各个功能的好坏。测试时需要我们编写测试程序,以实现自动化测试。
假设我们有一个板子,上面有A、B、C三个功能需要验证,A测试耗时1秒,B测试耗时2秒,C测试耗时3秒。一般的测试过程是按照A、B、C逐个进行测试,不难算出,测试完ABC这三个功能共耗时6秒。但是如果我们让这A、B、C同时开始测试,则只需耗时3秒,显然,比前面的测试时间缩少很多,并且测试的功能越多,缩少的时间就越多。
上面说的同时开始测试的方法,就是下面要介绍的多线程测试方法。为了便于理解,我将以实际代码来展示。
首先,我们根据第一中方法编写一个展示程序:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
/* 任务A */
int test_A(void)
{
/* 假设这个任务耗时为5秒钟 */
sleep(5);
printf("test A finish\n");
return 1;
}
/* 任务B */
int test_B(void)
{
/* 假设这个任务耗时为10秒钟 */
sleep(10);
printf("test B finish\n");
return 1;
}
/* 任务C */
int test_C(void)
{
/* 假设这个任务耗时为15秒钟 */
sleep(15);
printf("test C finish\n");
return 1;
}
int main(void)
{
int ret;
ret = test_A();
ret = test_B();
ret = test_C();
printf("test finish\n");
return 0;
}
然后我们编写一个多线程测试方法的展示程序:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
/* 任务1-3返回的结果保存在这里 */
static int result1;
static int result2;
static int result3;
/* 任务A */
void *thread1(void *arg)
{
/* 假设这个任务耗时为5秒钟 */
sleep(5);
printf("test A finish\n");
result1=1;
return (void*)&result1;
}
/* 任务B */
void *thread2(void *arg)
{
/* 假设这个任务耗时为10秒钟 */
sleep(10);
printf("test B finish\n");
result2=2;
return (void*)&result2;
}
/* 任务C */
void *thread3(void *arg)
{
/* 假设这个任务耗时为15秒钟 */
sleep(15);
printf("test C finish\n");
result3=3;
return (void*)&result3;
}
int main(int argc, char **argv)
{
pthread_t pt1,pt2,pt3;
if (pthread_create(&pt1, NULL, thread1, NULL) == -1){
goto thread1_create_fail;
}
if (pthread_create(&pt2, NULL, thread2, NULL) == -1){
goto thread2_create_fail;
}
if (pthread_create(&pt3, NULL, thread3, NULL) == -1){
goto thread3_create_fail;
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!