Skip to content

Commit 02d38b0

Browse files
committed
feat: add pthread examples
1 parent 3e675f2 commit 02d38b0

File tree

3 files changed

+77
-1
lines changed

3 files changed

+77
-1
lines changed

cpp_basics/thread

39.6 KB
Binary file not shown.

cpp_basics/thread.cpp

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/*
2+
* @Author: Chacha
3+
* @Date: 2022-03-03 13:51:04
4+
* @Last Modified by: Chacha
5+
* @Last Modified time: 2022-03-03 18:45:52
6+
*/
7+
8+
/**
9+
* 来源:https://www.runoob.com/cplusplus/cpp-multithreading.html
10+
*
11+
* C++ 多线程
12+
* 多线程是多任务处理的一种特殊形式,多任务处理允许让电脑同时运行两个或两个以上的程序。一般情况下,两种类型的多任务处理:基于进程和基于线程。
13+
* 1. 基于进程的多任务处理是程序的并发执行
14+
* 2. 基于线程的多任务处理是同一个程序片段的并发执行
15+
*
16+
* 多线程程序包含可以同时运行的两个或多个部分。这演的程序中每个部分称为一个线程,每个线程定义了一个单独执行路径。
17+
* 我们要使用 POSIX 编写多线程 C++ 程序。POSIX Threads 或 Pthreads 提供的 API 可在多种类 Unix POSIX 系统上可用,
18+
* 比如 FreeBSD、NetBSD、GNU/Linux、Mac OS X 和 Solaris。
19+
*
20+
* 创建线程
21+
* 下面的程序,我们可以用它来创建一个POSIX线程:
22+
* #include <pthread.h>
23+
* pthread_create (thread, attr, start_routine, arg)
24+
*
25+
* 在这里,pthread_create 创建一个新的线程,并让它可执行。下面是关于参数的说明:
26+
* 1. thread: 指向线程标志符指针。
27+
* 2. attr: 一个不透明的属性对象,可以被用来设置线程属性。您可以指定线程属性对象,也可以使用默认值 NULL。
28+
* 3. start_routine: 线程运行函数起始地址,一旦线程被创建就会执行。
29+
* 4. arg: 运行函数的参数。
30+
*
31+
* 创建线程成功时,函数返回 0,若返回值不为 0 则说明创建线程失败。
32+
*
33+
* 终止线程
34+
* 使用下面的程序,我们可以用它来终止一个 POSIX 线程:
35+
* #include <pthread.h>
36+
* pthread_exit (status)
37+
*
38+
* 在这里,pthread_exit 用于显式地退出一个线程。通常情况下,pthread_exit() 函数是在线程完成工作后无需继续存在时被调用。
39+
* 如果 main() 是在它所创建的线程之前结束,并通过 pthread_exit() 退出,那么其他线程将继续执行。否则,它们将在 main() 结束时自动被终止。
40+
*
41+
*/
42+
43+
#include <iostream>
44+
#include <pthread.h>
45+
46+
using namespace std;
47+
48+
#define NUM_THREADS 5
49+
50+
void *sayHello(void *ars)
51+
{
52+
cout << "Hello C++" << endl;
53+
return 0;
54+
};
55+
56+
int main(int argc, char const *argv[])
57+
{
58+
pthread_t tids[NUM_THREADS];
59+
60+
for (int i = 0; i < NUM_THREADS; i++)
61+
{
62+
// 参数依次是:创建的线程id,线程参数,调用的函数,传入的函数参数
63+
int ret = pthread_create(&tids[i], NULL, sayHello, NULL);
64+
65+
if (ret != 0)
66+
{
67+
cout << "pthread_create error: error_code=" << ret << endl;
68+
}
69+
}
70+
71+
// 等各个线程退出后,进程才结束,否则进程强制结束了,线程可能还没反应过来
72+
pthread_exit(NULL);
73+
74+
return 0;
75+
}

leetcode/dynamic_programming/dp_min_cost_climb_stairs.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
* @Author: Chacha
33
* @Date: 2022-03-02 16:09:51
44
* @Last Modified by: Chacha
5-
* @Last Modified time: 2022-03-02 18:57:41
5+
* @Last Modified time: 2022-03-03 10:46:46
66
*/
77

88
/**
@@ -81,6 +81,7 @@ int Solution::minCostClimbingStairs(vector<int> cost)
8181
dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i];
8282
}
8383

84+
// 最后一步可以理解为不用花费,所以取倒数第一步,第二步的最少值
8485
return min(dp[cost.size() - 1], dp[cost.size() - 2]);
8586
};
8687

0 commit comments

Comments
 (0)