首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PThread创建不创建线程

PThread创建不创建线程
EN

Stack Overflow用户
提问于 2017-03-18 09:14:47
回答 1查看 457关注 0票数 1
代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "pthread.h"
#include "semaphore.h"

FILE * f;
sem_t * s1;
sem_t * s2;
int check;
int  v1;
int  v2;
int i;

static void * client (void *arg){


    sem_getvalue(s1, &v1); printf("Client pre wait(S1) in S1 => S1 = %d\n",v1);
    sem_wait(s1);
    printf("client works...\n");
    check = sem_getvalue(s1, &v1); printf("Client.wait(S1) in S1 => S1 = %d\n",v1);
    if(check != 0) printf("sem_getvalue error");


     return 0;
    }


int main(void){

    pthread_t tidc;
    pthread_t tids;
    int rc;
    int rs;

    //Semaforo 1
    s1 = (sem_t *) malloc(sizeof(sem_t));
    check = sem_init (s1, 0, 2);
    if (check != 0) perror("s1_init failed");




    sem_getvalue(s1, &v1);

    printf("Create the semaphores: S1 = %i\n",v1 );

    sem_wait(s1);
    printf("main waits\n");
    sem_getvalue(s1, &v1); printf("Main.wait(S1) in S1 => S1 = %d\n",v1);

    rc = pthread_create (&tidc, NULL, client, 0);
    printf(" thread created ==> rc= %i\n",rc);


    return 0;

   }

它返回这个输出:

代码语言:javascript
复制
Create the semaphores: S1 = 2
main waits
Main.wait(S1) in S1 => S1 = 1
 thread created ==> rc= 0

有时这是:

代码语言:javascript
复制
 Create the semaphores: S1 = 2
main waits
Main.wait(S1) in S1 => S1 = 1
 thread created ==> rc= 0
Client pre wait(S1) in S1 => S1 = 1
Client pre wait(S1) in S1 => S1 = 1
client works...
Client.wait(S1) in S1 => S1 = Client.wait(S1) in S1 => S1 = 0

似乎有时会产生两个线程,有时却没有人。我用gcc prog.c -lpthred编译,甚至用gcc -pthread prog.c编译

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-18 09:25:58

如果多线程程序在一次执行到另一次执行时不执行相同的操作,则可能是因为未初始化的变量(如非线程程序中的变量),但也可能是因为https://stackoverflow.com/questions/34510/what-is-a-race-condition

在这种情况下,争用条件在线程执行和程序退出之间。

由于在创建线程后立即退出主线程,线程将终止(main thread exit, does other exit too?)。有时,线程有时间做一些事情,这取决于操作系统的状态和加载。

如果在主程序中添加一些实际处理、长延迟或对pthread_join(tdic,NULL);的调用以等待线程终止,则将具有确定性行为。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42872498

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档