C语言怎样实现多线程

Python018

C语言怎样实现多线程,第1张

package cn.sdeit.file

import java.io.BufferedReader

import java.io.File

import java.io.FileInputStream

import java.io.FileNotFoundException

import java.io.IOException

import java.io.InputStream

import java.io.InputStreamReader

import java.util.Scanner

public class ReadTxt

{

private int id

public String getArticle(String path,int id)

{

String url = path+id+".txt"

String string = ""

String allString = ""

File file=new File(url)

try

{

BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"utf-8"))

while((string=reader.readLine())!=null)

{

allString += string+"\r\n"

}

} catch (FileNotFoundException e)

{

e.printStackTrace()

} catch (IOException e)

{

e.printStackTrace()

}

return allString

}

}

因为您传入的是t的地址:rc = pthread_create(&thread[t], NULL, PrintHello, &t)

所以在PrintHello函数中thread_arg = (int)(*((int*)args))读取时会读取到t的最新值,即8.

这是因为主线程一直在执行,for( t = 0t <NUM_THREADSt++ )很快执行完,跳出循环t的值为8,而在PrintHello中sleep(1)肯定会读取到t的最新值8.

直接传t的值即可,如下:

#include<stdio.h>

#include <stdio.h>

#include <stdlib.h>

#include <stdint.h> // 加入这个头文件

#include <pthread.h>

#include <unistd.h>

#define    NUM_THREADS     8

void *PrintHello(void *args)

{

          int thread_arg

          sleep(1)

          thread_arg = (int)(uintptr_t)args //这样读取传来的t的值

          printf("Hello from thread %d\n", thread_arg)

          return NULL

}

int main(void)

{

        int rc,t

        pthread_t thread[NUM_THREADS]

        for( t = 0 t < NUM_THREADS t++ )

        { 

            printf("Creating thread %d\n", t)

            rc = pthread_create(&thread[t], NULL, PrintHello, (void *)(uintptr_t)t) // 这样传t的值

            if (rc)

            {

                printf("ERROR return code is %d\n", rc)

                return EXIT_FAILURE

            }

        }

        sleep(5)

        for( t = 0 t < NUM_THREADS t++ )

            pthread_join(thread[t], NULL)

        return EXIT_SUCCESS

}

如果针对问的问题来说, 可以考虑使用同步机制. 可以查如mutex等同步机制.

另外, 我会建议...你应该使用单一个服务程序, 用缓存空间去接收要打印的讯息, 单一控制输出萤幕, 这样应该会比较好. 因为萤幕输出只有一个, 多线直接控制, 本来就不好处理. 如果采用传送讯息机制, 应该就有顺序分别, 不易产生问题.