Ubuntu下gcc编译多线程程序的步骤
导读:在Ubuntu下使用GCC编译多线程程序,需要遵循以下步骤: 首先,确保你的系统已经安装了GCC和pthread库。如果没有安装,可以使用以下命令进行安装: sudo apt-get update sudo apt-get instal...
在Ubuntu下使用GCC编译多线程程序,需要遵循以下步骤:
- 首先,确保你的系统已经安装了GCC和pthread库。如果没有安装,可以使用以下命令进行安装:
sudo apt-get update
sudo apt-get install build-essential
- 创建一个名为
main.c
的C源文件,并在其中编写多线程程序。例如:
#include<
stdio.h>
#include <
stdlib.h>
#include <
pthread.h>
void* print_message(void* ptr) {
char* message;
message = (char*) ptr;
printf("%s\n", message);
return NULL;
}
int main() {
pthread_t thread1, thread2;
char* message1 = "Thread 1";
char* message2 = "Thread 2";
int rc1, rc2;
rc1 = pthread_create(&
thread1, NULL, print_message, (void*) message1);
rc2 = pthread_create(&
thread2, NULL, print_message, (void*) message2);
if (rc1 || rc2) {
printf("Error: unable to create threads\n");
exit(-1);
}
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
- 使用GCC编译器编译源文件。在终端中,导航到包含
main.c
的目录,然后运行以下命令:
gcc -o main main.c -lpthread
这将编译main.c
文件,并链接pthread库(-lpthread
选项)。编译后的可执行文件名为main
。
- 运行编译后的程序:
./main
这将输出两条消息,分别来自两个线程。请注意,由于线程调度的不确定性,输出的顺序可能会有所不同。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: Ubuntu下gcc编译多线程程序的步骤
本文地址: https://pptw.com/jishu/697956.html