一个 process 使用多个 thread 是一种让程序平行处理的方式,
跟使用 multi processes 来实作平行程序的区别在於
multi threads 是共用同一个 virtual memory
这使得 thread 跟 thread 之间的传递资料比较容易(process 还要建立 pipe)
但相对的也比较危险
#include <pthread.h>
int pthreaqd_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start)(void *), void *arg);
// Returns 0 on sucess, or a positive error number on error
thread
:用来区别各个 thread 用,ID 的功能attr
:attributestart
:这个新的 thread 要执行的 functionarg
:塞进 start
这个 function 的参数#include <pthread.h>
void pthread_exit(void *retval);
取得自己的 thread ID
#include <pthread.h>
pthread_t pthread_self(void);
// Returns the thread ID of the calling thread
看看是不是同一个 thread
#include <pthread.h>
int pthread_equal(pthread_t t1, pthread_t, t2);
// Returns nonzero value if t1 and t2 are equal, otherwise 0
为了确保 thread 之间 terminate 的顺序,可以用 pthread_join()
#include <pthread.h>
int pthread_join(pthread_t thread, void **retval);
// Returns 0 on sucess, or a positive error number on error
代表 thread
执行完之後,自己 (main thread) 才会结束
这是为了避免 main thread) 都结束了,还留下一些 zombie process
另一种避免 zombie process 的方式,可一把一个 thread 给杀掉
#include <pthread.h>
int pthread_detach(pthread_t thread);
// Returns 0 on sucess, or a positive error number on error
可以把 thread
给杀掉
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void *
threadFunc(void *arg)
{
char *s = (char *) arg;
printf("%s", s);
return (void *) strlen(s);
}
int
main (int argc, char **argv)
{
pthread_t t1;
void *res;
int s;
s = pthread_create(&t1, NULL, threadFunc, "Hello world\n");
if (s != 0) {
fprintf(stderr, "error\n");
exit(EXIT_FAILURE);
}
printf("Message from main()\n");
s = pthread_join(t1, &res);
if (s != 0) {
fprintf(stderr, "error\n");
exit(EXIT_FAILURE);
}
printf("%hread returned $ld\nk", (long) res);
exit(EXIT_SUCCESS);
}
The Linux Programming Interface
天亮了 昨晚是平安夜 关於迷雾森林故事 秘密通道 Rocky 循着发光的脚印继续寻找爸爸妈妈的下落 ...
惯例先上成果图XD https://asciinema.org/a/439607 终於开机开到she...
文件 原文文件:Page migration 翻译: Non-LRU 分页迁移 ==========...
从地端 On-Premise的传统资讯部署,再到云端 Cloud的新形态部署模式,在这个转型过程初...
大家好! 今天要实作能输入网址的 RSS 阅读器。 我们进入今天的主题吧! 程序码 Felix('f...