Linux 线程控制
为了方便理解资源划分的本质,这里直接通过编写代码从实践再到理论。
多线程角度理解资源"划分"
int pthread_create(pthread_t *restrict thread, const pthread_attr_t *restrict attr, void *(*start_routine)(void *), void *restrict arg); 功能:创建一个新的线程(注意:该函数是第三方库,不属于 C/C++)
参数:thread:返回线程 ID(输出型参数)attr:设置线程的属性 (优先级,栈大小之类),attr 为 NULL 表示使用默认属性 start_routine:回调函数 (函数指针类型),线程启动后要执行的函数 arg:传给线程启动函数的参数
返回值:成功返回 0;失败返回错误码
void *thread_routine(void *arg) {
std::string name = (const char *)(arg);
// 第二个死循环
while (true) {
std::cout << "我是新线程...,名字:" << name << ", pid: " << getpid() << std::endl;
sleep(1);
}
}
int main() {
fun();
pthread_t tid;
pthread_create(&tid, NULL, thread_routine, (void *)"thread-1");
while (true) {
std::cout << "我是主线程..., pid: " << getpid() << std::endl;
sleep(1);
}
return 0;
}
我们之前讲过如果是使用第三方库必须要指令库名称,而库路径是可以被放到特定路径下的。
g++ *.cc -pthread(指定库名称)
编译执行该可执行程序后:













