#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
int shared_resource = 0;
pthread_mutex_t mutex;
void *thread_function(void *arg)
{
while (1)
{
printf("0\n");
pthread_mutex_lock(&mutex);
printf("1\n");
sleep(2);
printf("2\n");
pthread_mutex_unlock(&mutex);
printf("3\n");
}
pthread_exit(NULL);
}
void *thread_function1(void *arg)
{
while (1)
{
printf("thread_function1\n");
sleep(1);
}
pthread_exit(NULL);
}
int main()
{
pthread_t threads[2];
pthread_mutex_init(&mutex, NULL);
int result = pthread_create(&threads[0], NULL, thread_function, NULL);
int result1 = pthread_create(&threads[1], NULL, thread_function1, NULL);
for (int i = 0; i < 2; i++)
{
pthread_join(threads[i], NULL);
}
pthread_mutex_destroy(&mutex);
return 0;
}
要编译并运行这个多线程的程序,你可以按照以下步骤在Linux中操作:
1. **编写程序文件**:将你的程序保存为一个文件,比如 `pthread_example.c`。
2. **使用编译器编译程序**:打开终端,进入保存程序的目录,然后使用以下命令编译程序:
```bash
gcc pthread_example.c -o pthread_example -pthread
```
- `gcc` 是 GNU 编译器集合中的 C 编译器。
- `pthread_example.c` 是你的源代码文件。
- `-o pthread_example` 指定输出的可执行文件名为 `pthread_example`。
- `-pthread` 参数告诉编译器链接 pthread 库,因为你的程序中使用了 pthread 多线程库。
3. **运行可执行文件**:编译成功后,你可以运行生成的可执行文件:
```bash
./pthread_example
```
这会在终端启动你的多线程程序。
4. **注意事项**:
- 确保你的系统安装了 pthread 库。大多数 Linux 发行版默认安装了这个库,但如果编译时出现链接错误,可能需要安装 `libpthread` 包。
- 如果程序中的 `sleep()` 函数没有作用,可以检查是否有其他线程在运行导致程序流程被占用。
- 在多线程程序中使用互斥锁(mutex)确保线程安全性,避免竞态条件。
通过这些步骤,你就能成功编译并在Linux中运行你的多线程程序了。