# 2022 quiz6 contributed by <shawn5141> EXP1 = parent_tid EXP2 = child_tid ### Clone system call #### CLONE_FLAGS is passed to clone system call. ```cpp= #define CLONE_FLAGS \ (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | \ CLONE_SYSVSEM | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID) ``` 這些 flag 指名 clone 需要擁有下列特性。 > CLONE_VM: the calling process and the child process run in the same memory space. > CLONE_FS: the caller and the child process share the same filesystem information > CLONE_FILES: the calling process and the child process share the same file descriptor table > CLONE_SIGHAND: the calling process and the child process share the same table of signal handlers > CLONE_THREAD: the child is placed in the same thread group as the calling process > CLONE_SYSVSEM: then the child and the calling process share a single list of System V semaphore adjustment (semadj) values. > CLONE_PARENT_SETTID: Store the child thread ID at the location pointed to by parent_tid. > CLONE_CHILD_CLEARTID: Clear (zero) the child thread ID at the location pointed to by child_tid. ```cpp thread_t tid = clone(wrap, (char *) thread_stack + STACK_SZ + GUARD_SZ, CLONE_FLAGS, fa, &(node->tid), NULL, &(node->tid)); ``` ### spin_lock ### mutex ### futex [futex 綜敘](http://blog.foool.net/2021/04/futex-%E7%BB%BC%E8%BF%B0/) 竞争态总是很少发生的,只有在竞争态才需要进入内核,否则在用户态即可完成。futex的两个目标是:1)尽量避免系统调用;2)避免不必要的上下文切换(导致的TLB失效等)。 > 注意:futex 在Linux 的内核实现为一个系统调用(SYS_futex),用户程序如果直接调用它肯定会进入内核态,它还需要和其他语句(如原子操作)配合使用,新手在未理解其futex 原理和并发控制机制时极易犯错,这也是为什么不推荐直接使用它的原因。 ``` syscall(SYS_futex, m, FUTEX_WAIT, 1, NULL, NULL, 0); ``` [lock in golang video](https://www.youtube.com/watch?v=7OpCf6f_BAM&t=1047s) ref: https://www.youtube.com/watch?v=wPfPuliEI5M