MCPcopy Create free account
hub / github.com/ChunelFeng/CThreadPool / tutorial_threadpool_2

Function tutorial_threadpool_2

tutorial.cpp:39–88  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

37
38
39void tutorial_threadpool_2(UThreadPoolPtr tp) {
40 /**
41 * 通过添加工作组(taskGroup)来执行任务
42 */
43 UTaskGroup taskGroup;
44
45 /** 添加一个不耗时的任务 */
46 int i = 1, j = 2, k = 3;
47 auto hcg = [] { CGRAPH_ECHO("Hello, CGraph."); };
48 taskGroup.addTask(hcg);
49
50 /** 添加一个耗时为1000ms的任务 */
51 taskGroup.addTask([i, j] {
52 int result = i + j;
53 CGRAPH_SLEEP_MILLISECOND(1000)
54 CGRAPH_ECHO("sleep for 1 second, [%d] + [%d] = [%d], run success.", i, j, result);
55 });
56
57 taskGroup.addTask([i, j, k] {
58 int result = i - j + k;
59 CGRAPH_SLEEP_MILLISECOND(2000)
60 CGRAPH_ECHO("sleep for 2 second, [%d] - [%d] + [%d] = [%d], run success.", i, j, k, result);
61 return result; // submit接口,不会对线程函数返回值进行判断。如果需要判断,考虑commit方式
62 });
63
64 /** 如果添加耗时3000ms的任务,则整体执行失败 */
65 /* taskGroup.addTask([] {
66 CGRAPH_SLEEP_MILLISECOND(3000)
67 }); */
68
69 /**
70 * 可以添加执行task group结束后的回调信息
71 * 其中sts是task group整体执行结果的返回值信息
72 * */
73 /* taskGroup.setOnFinished([] (const CStatus& sts) {
74 if(sts.isOK()) {
75 CGRAPH_ECHO("task group run success.");
76 } else {
77 CGRAPH_ECHO("task group run failed, error info is [%s].", sts.getInfo().c_str());
78 }
79 }); */
80
81 /**
82 * 设定超时时间=2500ms,确保以上任务能顺利执行完成
83 * 如果加入sleep(3000)的任务,则也会在2500ms的时候退出
84 * 并且在status中提示超时信息
85 * */
86 CStatus status = tp->submit(taskGroup, 2500);
87 CGRAPH_ECHO("task group run status is [%d].", status.getCode());
88}
89
90
91void tutorial_threadpool_3(UThreadPoolPtr tp) {

Callers 1

mainFunction · 0.85

Calls 3

CGRAPH_ECHOFunction · 0.85
submitMethod · 0.80
getCodeMethod · 0.80

Tested by

no test coverage detected