在事先安装好的Linux+GCC环境下编译、运行Pthreads程序
时间: 2023-07-15 11:10:33 浏览: 78
下面是在Linux+GCC环境下编译、运行Pthreads程序的步骤:
1. 编写Pthreads程序。这里以一个简单的例子来说明,该程序创建了两个线程,分别执行函数thread_func1和thread_func2,然后等待这两个线程结束。代码如下:
```c
#include <stdio.h>
#include <pthread.h>
void *thread_func1(void *arg)
{
printf("Thread 1 is running.\n");
pthread_exit(NULL);
}
void *thread_func2(void *arg)
{
printf("Thread 2 is running.\n");
pthread_exit(NULL);
}
int main()
{
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, thread_func1, NULL);
pthread_create(&tid2, NULL, thread_func2, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
printf("Main thread is exiting.\n");
return 0;
}
```
2. 保存上述代码到一个文件中,例如pthread_demo.c。
3. 打开终端,进入存放pthread_demo.c文件的目录。
4. 输入以下命令进行编译:
```
gcc pthread_demo.c -o pthread_demo -lpthread
```
其中,-o pthread_demo表示输出文件名为pthread_demo,-lpthread表示链接pthread库。
5. 编译成功后,输入以下命令运行程序:
```
./pthread_demo
```
6. 如果程序正常运行,终端会依次输出以下内容:
```
Thread 1 is running.
Thread 2 is running.
Main thread is exiting.
```
这表明程序已经成功创建了两个线程,并且这两个线程分别执行了thread_func1和thread_func2函数。最后,主线程等待这两个线程结束后才退出。