证明线程确实共享内存
实践:
++x
Hello from thread 2
Hello from thread 7
Hello from thread 3
Hello from thread 4
Hello from thread 5
Hello from thread 6
Hello from thread 8
Hello from thread 9
Hello from thread B
Hello from thread A
x++
Hello from thread 1
Hello from thread 2
Hello from thread 3
Hello from thread 4
Hello from thread 5
Hello from thread 6
Hello from thread 7
Hello from thread 8
Hello from thread 9
Hello from thread A
多处理器编程:从入门到放弃 http://jyywiki.cn/OS/2022/slides/3.slides#/1/4
入门:thread.h 简化的线程 API
我们为大家封装了超级好用的线程 API (thread.h)
create(fn)- 创建一个入口函数是
fn的线程,并立即开始执行void fn(int tid) { ... }- 参数
tid从 1 开始编号
- 语义:在状态中新增 stack frame 列表并初始化为
fn(tid)
- 创建一个入口函数是
join()- 等待所有运行线程的
fn返回 - 在
main返回时会自动等待所有线程结束 - 语义:在有其他线程未执行完时死循环,否则返回
- 等待所有运行线程的
- 编译时需要增加
-lpthread
线程库
thread.h
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdatomic.h>
#include <assert.h>
#include <unistd.h>
#include <pthread.h>
#define NTHREAD 64
enum { T_FREE = 0, T_LIVE, T_DEAD, };
struct thread {
int id, status;
pthread_t thread;
void (*entry)(int);
};
struct thread tpool[NTHREAD], *tptr = tpool;
void *wrapper(void *arg) {
struct thread *thread = (struct thread *)arg;
thread->entry(thread->id);
return NULL;
}
void create(void *fn) {
assert(tptr - tpool < NTHREAD);
*tptr = (struct thread) {
.id = tptr - tpool + 1,
.status = T_LIVE,
.entry = fn,
};
pthread_create(&(tptr->thread), NULL, wrapper, tptr);
++tptr;
}
void join() {
for (int i = 0; i < NTHREAD; i++) {
struct thread *t = &tpool[i];
if (t->status == T_LIVE) {
pthread_join(t->thread, NULL);
t->status = T_DEAD;
}
}
}
__attribute__((destructor)) void cleanup() {
join();
}
gcc -lpthread
#include "thread.h" void Ta(){while(1){printf("+++");}} void Tb(){while(1){printf("___");}} int main(){ create(Ta); create(Tb); } // gcc multiThreaded.c -lpthread && ./a.out
#include "thread.h" int x=0; void Thello(int id){ usleep(id*1000); printf("Hello from thread %c\n","123456789ABCDEF"[x++]); } int main(){ for(int i=0;i<10;i++){ create(Thello); } }

浙公网安备 33010602011771号