[英]PThread Create doesn't create a thread
#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;
}
它返回此輸出:
Create the semaphores: S1 = 2
main waits
Main.wait(S1) in S1 => S1 = 1
thread created ==> rc= 0
有時這個:
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
如果一個多線程程序從一個執行到另一個執行沒有做同樣的事情,那可能是因為未初始化的變量(比如在非線程程序中),但也可能是因為競爭條件 。
在這種情況下,競爭條件在線程執行和程序退出之間。
由於您在創建線程后立即退出主線程,因此線程終止( 主線程退出,其他也退出? )。 有時,線程有時間做某事,具體取決於操作系統狀態和負載。
如果添加一些實際處理,長時間延遲或調用pthread_join(tdic,NULL);
要等待主程序中的線程終止,您將具有確定性行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.