用C创建线程 [英] Creating Threads in C

查看:62
本文介绍了用C创建线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个创建线程的代码。线程写入文件。如果已创建线程,则返回0。这里的代码返回0,但它确实进入函数write()但不写入文件。只是为了检查它进入函数我已经放了一个printf()语句。以下是代码: -

I am trying to implement a code which creates a thread. The thread writes into a file. If the thread has been created it returns 0 . The code here returns 0 but it does go into the fuction write() but does not writes in the file . Just to check it goes in the function i have put a printf() statement . Here is the code :-

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

void *write(void *arg)
{

  printf("HI \n");
  FILE *fp;
  fp=fopen("file.txt","a");

  if(fp==NULL)
    {
      printf("error\n");
    }
else{
  fprintf(fp,"hello world");
  
 }
main()
{
  pthread_t thread;
  int tid;
  tid=pthread_create(&thread,NULL,write,NULL);
  printf("thread1 return %d \n",tid);
  exit(0);
}

推荐答案

主要不需要在线程完成之前退出所以我们必须在主pthead_join中添加另一个函数( )。这是编辑后的代码

The main need not to exit before the thread finishes so we have to add another function in main pthead_join () . Here is the edited code
  main()
{
  thread_t thread;
  int tid;
  tid=pthread_create(&thread,NULL,write,NULL);
  printf("thread1 return %d \n",tid);
  pthread_join(thread, NULL);
  exit(0);
}


这篇关于用C创建线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆