1 What are Threads?
- 一个进程可以有多个线程
- 线程共享进程的资源,多进程是复制内存空间,彼此独立
- 线程被OS调度,意味着一个进程会使用超过100%的cpu(多核系统)
2 Hello POSIX Threads?
- POSIX became the standard interface for many system(C,Java,Python)
2.1 Creating a Thread
/* hello_pthread.c*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
void * hello_fun(void * args){
printf("Hello World!\n");
return NULL;
}
int main(int argc, char * argv[]){
pthread_t thread; //thread identifier
//create a new thread have it run the function hello_fun
pthread_create(&thread, NULL, hello_fun, NULL);
//wait until the thread completes
pthread_join(thread, NULL);
return 0;
}
pthread_create()
创建线程,运行hello_fun
,并用thread
指针接收pthread_join()
主线程阻塞,直到thread
执行结束int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
2.2 Passing Arguments to a Thread
/* hello_args_pthread.c*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
void * hello_arg(void * args){
char * str = (char *) args;
printf("%s", str);
return NULL;
}
int main(int argc, char * argv[]){
char hello[] = "Hello World!\n";
pthread_t thread; //thread identifier
//create a new thread that runs hello_arg with argument hello
pthread_create(&thread, NULL, hello_arg, hello);
//wait until the thread completes
pthread_join(thread, NULL);
return 0;
}
2.3 Joining Threads
- thread的join很像process的wait
- 线程之间可以相互join
3.当主线程退出时,其他所有线程自动销毁,所以不会产生僵尸和浪费资源
/* hello_pthread_bad.c*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
void * hello_fun(){
printf("Hello World!\n");
return NULL;
}
int main(int argc, char * argv[]){
pthread_t thread;
pthread_create(&thread, NULL, hello_fun, NULL);
return 0;
}
2.4 Return values from threads
1.int pthread_join(pthread_t thread, void **retval);
2.类似于进程中的exit
函数传递进程退出的状态,线程可以返回任何参数
2.5 Compiling POSIX threads
3 Threads and the OS
- 系统层面,pid和tid是相同的,既主线程和进程的id是相同的
- 线程内部tid和pid是不同的
/* hello_id_pthread.c*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <pthread.h>
//have to call syscall directly, no libc wrapper
pid_t gettid(){
return (pid_t) syscall (SYS_gettid);
}
void * hello_fun(void * args){
//retrieve the thread_id
pthread_t thread = pthread_self();
//print all identifying information
printf("THREAD: TID:%d PID:%d PthreadID:%lu\n", gettid(), getpid(), thread);
return NULL;
}
int main(int argc, char * argv[]){
pthread_t thread; //thread identifier
//create a new thread have it run the function hello_fun
pthread_create(&thread, NULL, hello_fun, NULL);
//print all identifying information
printf("MAIN: TID:%d PID:%d \n", gettid(), getpid());
//wait until the thread completes
pthread_join(thread, NULL);
return 0;
}
3.2 Threads Running Like Processes
- C中每个线程可以占用一个cpu核
参考:
https://www.usna.edu/Users/cs/aviv/classes/ic221/s16/lec/28/lec.html#coderef-bad_ref