C语言多线程编程,线程序号输出
时间: 2024-01-25 07:03:32 浏览: 28
在C语言中,可以使用`pthread_self()`函数获取当前线程的ID。可以通过将返回值强制转换为`unsigned long`类型来输出线程序号。以下是一个简单的示例代码:
```c
#include <stdio.h>
#include <pthread.h>
void* thread_func(void* arg)
{
printf("Thread #%lu is running.\n", (unsigned long)pthread_self());
return NULL;
}
int main()
{
pthread_t t1, t2;
pthread_create(&t1, NULL, thread_func, NULL);
pthread_create(&t2, NULL, thread_func, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return 0;
}
```
该示例代码创建了两个线程`t1`和`t2`,并在每个线程中输出其线程ID。在主函数中,等待两个线程完成后结束程序。当程序运行时,可以看到类似以下的输出:
```
Thread #140348987168768 is running.
Thread #140348978775040 is running.
```
每个线程的ID是唯一的,并可以用于标识不同的线程。
相关问题
c语言多线程编程
C语言中,多线程编程可以使用pthread库来实现。使用pthread库需要包含头文件pthread.h。
下面是一个简单的多线程程序示例:
```
#include <stdio.h>
#include <pthread.h>
void *start_routine(void *arg) {
printf("Hello from thread!\n");
pthread_exit(NULL);
}
int main() {
pthread_t thread;
pthread_create(&thread, NULL, start_routine, NULL);
pthread_join(thread, NULL);
printf("Thread finished.\n");
return 0;
}
```
在上面的示例中,我们定义了一个start_routine函数作为线程的入口点。在主函数中,我们使用pthread_create函数创建一个新线程,并将start_routine函数作为线程的入口点。然后,我们使用pthread_join函数等待线程完成,最后输出一条消息表示线程已经结束。
这只是一个简单的例子,实际上多线程编程涉及到更多的概念和技术,例如线程同步、线程间通信等。如果你想深入了解多线程编程,建议阅读相关的书籍或者在线教程。
写一个基于linux下C语言多线程编程
的例子。
好的,我可以为您提供一个简单的例子:
```c
#include <stdio.h>
#include <pthread.h>
void *print_hello(void *arg) {
printf("Hello from thread %d\n", *(int*)arg);
pthread_exit(NULL);
}
int main() {
const int num_threads = 3;
pthread_t threads[num_threads];
int thread_args[num_threads];
for(int i=0; i<num_threads; ++i) {
thread_args[i] = i;
pthread_create(&threads[i], NULL, print_hello, &thread_args[i]);
}
for(int i=0; i<num_threads; ++i) {
pthread_join(threads[i], NULL);
}
return 0;
}
```
该程序会创建三个线程,每个线程会打印一条消息。在主线程中,我们使用 `pthread_join` 等待每个线程结束。