(16) 函数 thrd_detach ()。因为至少线程控制块 TCB 要回收。类似于进程控制块 PCB 被父进程回收, 父进程要调用 wait_pid():
(17) 函数 thrd_equal () :
++ 给出举例:
#include <stdio.h>
#include <stdlib.h>
#include <threads.h>
void* thread_function(void* arg) {
// 线程函数体
return NULL;
}
int main() {
thrd_t thread1, thread2;
int result1, result2;
// 创建两个线程
result1 = thrd_create(&thread1, thread_function, NULL);
if (result1 != thrd_success) {
fprintf(stderr, "Failed to create thread 1\n");
return EXIT_FAILURE;
}
result2 = thrd_create(&thread2, thread_function, NULL);
if (result2 != thrd_success) {
fprintf(stderr, "Failed to create thread 2\n");
return EXIT_FAILURE;
}
// 比较线程标识符
if (thrd_equal(&thread1, &thread2)) {
printf("Thread 1 and Thread 2 are the same thread.\n");
} else {
printf("Thread 1 and Thread 2 are different threads.\n");
}
// 等待线程完成
thrd_join(thread1, NULL);
thrd_join(thread2, NULL);
return EXIT_SUCCESS;
}
(18) 函数 thrd_current() :
(19)函数 thrd_yield():
++ 给出 举例:
#include <threads.h>
#include <stdio.h>
#include <stdlib.h>
// 线程函数
void* thread_function(void* arg) {
for (int i = 0; i < 10; ++i) {
printf("Thread %ld running... %d\n", (long)arg, i);
// 在每次循环中调用 thrd_yield()
thrd_yield();
}
return NULL;
}
int main() {
thrd_t thread1, thread2;
// 创建两个线程
thrd_create(&thread1, thread_function, (void*)1L);
thrd_create(&thread2, thread_function, (void*)2L);
// 等待两个线程完成
thrd_join(thread1, NULL);
thrd_join(thread2, NULL);
return 0;
}
但是该源代码 在 ubantu 与 vs2019 里的 c17 标准下都找不到系统函数。无法验证。
(20)
谢谢