【问题标题】:Linux - Using mutex to synchonise serial portLinux - 使用互斥锁同步串口
【发布时间】:2018-09-27 13:51:59
【问题描述】:

我正在为 Linux 操作系统编写 C 程序。
程序可以启动一个定时器:主程序和定时器都可以在串口上发送和接收字符。
我的尝试是通过一个全局结构中的互斥锁序列化串行端口访问,该结构在打开时初始化为:

if (pthread_mutex_init( &pED->lockSerial, NULL) != 0)
{   
    lwsl_err("lockSerial init failed\n");
}

我保护了所有在端口上发送数据的函数如下:

ssize_t cmdFirmwareVersion(EngineData *pED)
{
  if (pED->fdSerialPort==-1)
    return -1;

  LOCK_SERIAL;
  unsigned char cmd[] = { 0x00, 0x00, 0x7F };
  write( pED->fdSerialPort, cmd, sizeof(cmd));
  int rx = read ( pED->fdSerialPort, rxbuffer, sizeof rxbuffer);
  dump( rxbuffer, rx);
  UNLOCK_SERIAL;
  return rx;
}

在哪里

#define LOCK_SERIAL if (0!=pthread_mutex_lock(&pED->lockSerial)) {printf("Err lock");return 0;}
#define UNLOCK_SERIAL   pthread_mutex_unlock(&pED->lockSerial);

运行程序并启动计时器我看到请求是有规律的。当我以其他方式(从 rx websocket 函数)触发其中一个调用时,程序挂起,我需要杀死它。

为什么整个程序都停止了??

【问题讨论】:

    标签: linux serial-port synchronization mutex


    【解决方案1】:

    如果进程挂起,可能是由于循环等待互斥锁或持有互斥锁并试图再次锁定它。这可能会导致死锁。

    如果线程正在等待资源,则输出将显示线程的状态为 D 或 S。它会在进程挂起时出现。

                   D    uninterruptible sleep (usually IO)
                   S    interruptible sleep (waiting for an event to complete)
    

    我创建了一个线程来保存互斥锁并尝试再次锁定它。 ps 输出和 GDB 显示主线程和子线程处于睡眠状态。

    xxxx@virtualBox:~$ ps -eflT |grep a.out
    0 S root      3982  3982  2265  0  80   0 - 22155 -      20:28 pts/0    00:00:00 ./a.out
    1 S root      3982  3984  2265  0  80   0 - 22155 -      20:28 pts/0    00:00:00 ./a.out
    
    (gdb) info threads 
      Id   Target Id         Frame 
    * 1    Thread 0x7ffff7fdf740 (LWP 4625) "a.out" 0x00007ffff7bbed2d in     __GI___pthread_timedjoin_ex (
        threadid=140737345505024, thread_return=0x0, abstime=0x0, block=    <optimized out>) at pthread_join_common.c:89
      2    Thread 0x7ffff77c4700 (LWP 4629) "a.out" __lll_lock_wait ()
        at ../sysdeps/unix/sysv/linux/x86_64/lowlevellock.S:135
    

    请查看博客Tech Easy 了解有关线程的更多信息。

    【讨论】:

      猜你喜欢
      • 2011-06-10
      • 2012-08-28
      • 1970-01-01
      • 2014-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多