相关疑难解决方法(0)

如何使用pthreads屏障?

嗨很抱歉发布了一大堆代码,但我是C代码的新手,基本上我正在做大学的任务,我必须实现一个"pthread_barrier",现在我理解了障碍的概念(或者在至少我认为我这样做但是我只是不确定我应该把它放在哪里.作业说明:

"使用pthread_barrier_init和pthread_barrier_wait确保所有生产者/消费者线程同时开始生产/消费."

顺便说一下,这是作业的额外学分

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

#define SIXTY_SECONDS 60000000
#define ONE_SECOND 1000000
#define RANGE 10
#define PERIOD 2

typedef struct {
  int *carpark;
  int capacity;
  int occupied;
  int nextin;
  int nextout;
  int cars_in;
  int cars_out;
  pthread_mutex_t lock;
  pthread_cond_t space;
  pthread_cond_t car;
  pthread_barrier_t bar;
} cp_t;

/* Our producer threads will each execute this function */
static void *
producer(void *cp_in)
{    
  cp_t *cp;
  unsigned int seed;
  /* Convert what was passed in to a pointer …
Run Code Online (Sandbox Code Playgroud)

c linux pthread-barriers

6
推荐指数
1
解决办法
2万
查看次数

在Linux上执行pthread

我开始在linux上进行pthread编程,在第一个程序中我完全搞糊涂了.以下是我正在运行的程序

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

void *print_message_function( void *ptr );

int main(){
 pthread_t thread1, thread2;
 char *message1 = "Thread 1";
 char *message2 = "Thread 2";
 int  iret1, iret2;

/* Create independent threads each of which will execute function */

 iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
 iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);

 /* Wait till threads are complete before main continues. Unless we  */
 /* wait we run the risk of executing an exit which …
Run Code Online (Sandbox Code Playgroud)

c linux pthreads

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

传递给 pthread_create 的例程何时开始?

给出以下代码

#include <pthread.h>

void *pt_routine(void *arg)
{
    pthread_t *tid;
    tid = (pthread_t *) arg;
    /* do something with tid , say printf?*/
    /*
    printf("The thread ID is %lu\n", *tid);
    */
    return NULL;
}

int main(int argc, char **argv)
{
    int rc;
    pthread_t tid;
    rc = pthread_create(&tid, NULL, pt_routine, &tid);
    if (rc)
    {
        return 1;
    }
    printf("The new thread is %lu\n", tid);
    pthread_join(tid, NULL);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

例行公事能永远正确吗tid

当然,我可以使用 pthread 来获取自身 ID,但我只是想知道例程何时运行。

c posix pthreads

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

标签 统计

c ×3

linux ×2

pthreads ×2

posix ×1

pthread-barriers ×1