#include <stdio.h> #include <stdlib.h> #include <pthread.h> #define NUM_THREADS 5 void *thread_func(void *thread_id) { long tid; tid = (long) thread_id; printf("Thread %ld is running\n", tid); // 创建一个新的线程 pthread_t sub_thread; int rc; rc = pthread_create(&sub_thread, NULL, thread_func, (void *) (tid + 1)); if (rc) { printf("Error: return code from pthread_create() is %d\n", rc); exit(-1); } pthread_exit(NULL); } int main(int argc, char *argv[]) { pthread_t threads[NUM_THREADS]; int rc; long t; for (t = 0; t < NUM_THREADS; t++) { printf("Creating thread %ld\n", t); rc = pthread_create(&threads[t], NULL, thread_func, (void *) t); if (rc) { printf("Error: return code from pthread_create() is %d\n", rc); exit(-1); } } // 等待所有线程结束 for (t = 0; t < NUM_THREADS; t++) { pthread_join(threads[t], NULL); } pthread_exit(NULL); }如何在第二个子线程里天机算法
时间: 2024-03-14 07:45:09 浏览: 72
您可以将您的算法代码放在`thread_func`函数中。在您创建新的子线程时,将`thread_func`作为参数传递给`pthread_create`函数,就可以在新的子线程中运行您的算法。以下是修改后的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 5
void *thread_func(void *thread_id) {
long tid;
tid = (long) thread_id;
printf("Thread %ld is running\n", tid);
// 在第二个子线程中添加算法
if (tid == 2) {
printf("Running algorithm in thread %ld\n", tid);
// 这里是您的算法代码
// ...
}
// 创建一个新的子线程
pthread_t sub_thread;
int rc;
rc = pthread_create(&sub_thread, NULL, thread_func, (void *) (tid + 1));
if (rc) {
printf("Error: return code from pthread_create() is %d\n", rc);
exit(-1);
}
pthread_exit(NULL);
}
int main(int argc, char *argv[]) {
pthread_t threads[NUM_THREADS];
int rc;
long t;
for (t = 0; t < NUM_THREADS; t++) {
printf("Creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, thread_func, (void *) t);
if (rc) {
printf("Error: return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
// 等待所有线程结束
for (t = 0; t < NUM_THREADS; t++) {
pthread_join(threads[t], NULL);
}
pthread_exit(NULL);
}
```
在函数`thread_func`中,当`tid`等于2时,您可以在该线程中运行您的算法。如果您需要访问共享资源,请考虑线程安全问题。
阅读全文