相关疑难解决方法(0)

线程创建期间程序执行的流程

我是新手.

我编写了一个示例程序来创建一个线程.

#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
#include<string.h>
#include<pthread.h>


void * func(void * temp)
{
    printf("inside function\n");
    return NULL;
}

int main()
{
    pthread_t pt1;
    printf("creating thread\n");
    pthread_create(&pt1,NULL,&func,NULL);
    printf("inside main created thread\n");

return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译后,答案是:

creating thread
inside main created thread
inside function
inside function
Run Code Online (Sandbox Code Playgroud)

我知道答案可能会在执行in func return 0;之前调用printf.但是如何在解决方案inside function中打印两次?

gcc -o temp thread1.c -lpthread 第一次运行时编译:

creating thread
inside main created thread
Run Code Online (Sandbox Code Playgroud)

第二轮:

creating thread
inside main created thread
inside function
inside function
Run Code Online (Sandbox Code Playgroud)

gcc …

c multithreading pthreads

8
推荐指数
1
解决办法
603
查看次数

pthread:一个printf语句在子线程中打印两次

这是我的第一个pthread程序,我不知道为什么printf语句在子线程中打印两次:

int x = 1;

void *func(void *p)
{
    x = x + 1;
    printf("tid %ld: x is %d\n", pthread_self(), x);
    return NULL;
}

int main(void)
{
    pthread_t tid;
    pthread_create(&tid, NULL, func, NULL);

    printf("main thread: %ld\n", pthread_self());

    func(NULL);
}
Run Code Online (Sandbox Code Playgroud)

在我的平台上观察到的输出(Linux 3.2.0-32-generic#51-Ubuntu SMP x86_64 GNU/Linux):

1.
main thread: 140144423188224
tid 140144423188224: x is 2

2.
main thread: 140144423188224
tid 140144423188224: x is 3

3.
main thread: 139716926285568
tid 139716926285568: x is 2
tid 139716918028032: x is 3
tid 139716918028032: x is …
Run Code Online (Sandbox Code Playgroud)

printf pthreads

5
推荐指数
1
解决办法
2930
查看次数

简单的pthread代码中的奇怪结果

我写了以下代码:

#include <pthread.h>
#include <stdio.h>

void* sayHello (void *x){
    printf ("Hello, this is %d\n", (int)pthread_self());
    return NULL;
}

int main (){
    pthread_t thread;
    pthread_create (&thread, NULL, &sayHello, NULL);
    printf("HERE\n");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译和运行后,我看到了3种不同类型的输出.

  1. 只打印了"Here".
  2. "这里"和1'sayHello'的消息.
  3. "这里"和2'sayHello'的消息.

当然我对第二个选项没关系,但是我不明白为什么如果我只创建一个线程,'sayHello'massege可以打印0或2次?

c multithreading pthreads

3
推荐指数
1
解决办法
92
查看次数

标签 统计

pthreads ×3

c ×2

multithreading ×2

printf ×1