* @brief Creates a new thread in a POSIX-compliant system. * * The `pthread_create` function initializes a new thread in the calling process. The new thread starts execution * by invoking the function specified by the `start` parameter. The thread runs concurrently with the calling thread. * * @param[out] pid * A pointer to a `pthread_t` object where the ID of the newly created thread will
| 386 | * @see pthread_join, pthread_exit, pthread_attr_init |
| 387 | */ |
| 388 | int pthread_create(pthread_t *pid, |
| 389 | const pthread_attr_t *attr, |
| 390 | void *(*start)(void *), void *parameter) |
| 391 | { |
| 392 | int ret = 0; |
| 393 | void *stack; |
| 394 | char name[RT_NAME_MAX]; |
| 395 | static rt_uint16_t pthread_number = 0; |
| 396 | |
| 397 | pthread_t pth_id; |
| 398 | _pthread_data_t *ptd; |
| 399 | |
| 400 | /* pid shall be provided */ |
| 401 | RT_ASSERT(pid != RT_NULL); |
| 402 | |
| 403 | /* allocate posix thread data */ |
| 404 | pth_id = _pthread_data_create(); |
| 405 | if (pth_id == PTHREAD_NUM_MAX) |
| 406 | { |
| 407 | ret = ENOMEM; |
| 408 | goto __exit; |
| 409 | } |
| 410 | /* get pthread data */ |
| 411 | ptd = _pthread_get_data(pth_id); |
| 412 | |
| 413 | RT_ASSERT(ptd != RT_NULL); |
| 414 | |
| 415 | if (attr != RT_NULL) |
| 416 | { |
| 417 | ptd->attr = *attr; |
| 418 | } |
| 419 | else |
| 420 | { |
| 421 | /* use default attribute */ |
| 422 | pthread_attr_init(&ptd->attr); |
| 423 | } |
| 424 | |
| 425 | if (ptd->attr.stacksize == 0) |
| 426 | { |
| 427 | ret = EINVAL; |
| 428 | goto __exit; |
| 429 | } |
| 430 | |
| 431 | rt_snprintf(name, sizeof(name), "pth%02d", pthread_number ++); |
| 432 | |
| 433 | /* pthread is a static thread object */ |
| 434 | ptd->tid = (rt_thread_t) rt_malloc(sizeof(struct rt_thread)); |
| 435 | if (ptd->tid == RT_NULL) |
| 436 | { |
| 437 | ret = ENOMEM; |
| 438 | goto __exit; |
| 439 | } |
| 440 | memset(ptd->tid, 0, sizeof(struct rt_thread)); |
| 441 | |
| 442 | if (ptd->attr.detachstate == PTHREAD_CREATE_JOINABLE) |
| 443 | { |
| 444 | ptd->joinable_sem = rt_sem_create(name, 0, RT_IPC_FLAG_FIFO); |
| 445 | if (ptd->joinable_sem == RT_NULL) |