使用ubantu直接进行代码调试的办法

#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中运行你的多线程程序了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

文武先生hh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值