如何在lazy_static宏中包含mysql :: Conn?

时间:2018-03-15 21:24:43

标签: mysql rust

此代码:

Monad

生成一条很长的错误消息:

#[macro_use]
extern crate lazy_static;
extern crate mysql;

use mysql::*;

fn some_fn() {
    lazy_static! {
        static ref CONNECTION: Conn = Conn::new("mysql://root:password@127.0.0.1:3306/mydb?prefer_socket=false").unwrap();
    }
}

是不是因为error[E0277]: the trait bound `*mut std::os::raw::c_void: std::marker::Sync` is not satisfied in `winapi::minwinbase::OVERLAPPED` --> src\main.rs:8:5 | 8 | / lazy_static! { 9 | | static ref CONNECTION: Conn = Conn::new("mysql://root:password@127.0.0.1:3306/mydb?prefer_socket=false").unwrap(); 10 | | } | |_____^ `*mut std::os::raw::c_void` cannot be shared between threads safely | = help: within `winapi::minwinbase::OVERLAPPED`, the trait `std::marker::Sync` is not implemented for `*mut std::os::raw::c_void` = note: required because it appears within the type `winapi::minwinbase::OVERLAPPED` = note: required because of the requirements on the impl of `std::marker::Sync` for `std::ptr::Unique<winapi::minwinbase::OVERLAPPED>` = note: required because it appears within the type `std::boxed::Box<winapi::minwinbase::OVERLAPPED>` = note: required because it appears within the type `named_pipe::Overlapped` = note: required because it appears within the type `named_pipe::PipeClient` = note: required because it appears within the type `std::option::Option<named_pipe::PipeClient>` = note: required because it appears within the type `std::io::BufWriter<named_pipe::PipeClient>` = note: required because it appears within the type `std::option::Option<std::io::BufWriter<named_pipe::PipeClient>>` = note: required because it appears within the type `bufstream::InternalBufWriter<named_pipe::PipeClient>` = note: required because it appears within the type `std::io::BufReader<bufstream::InternalBufWriter<named_pipe::PipeClient>>` = note: required because it appears within the type `bufstream::BufStream<named_pipe::PipeClient>` = note: required because it appears within the type `mysql::io::Stream` = note: required because it appears within the type `std::option::Option<mysql::io::Stream>` = note: required because it appears within the type `mysql::Conn` = note: required by `lazy_static::lazy::Lazy` = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info) 不打算在多线程应用程序中使用? 如果我的程序不是多线程并且我使用非线程安全类型,我如何使用lazy_static?

1 个答案:

答案 0 :(得分:1)

你的代码在macOS上工作得很好。我认为这是a bug with the implementation of the MySQL crate,作者同意,在不到一天的时间内解决了这个问题。您应该只需升级包就可以使用原始代码。

作为临时解决方法,您可以将Conn打包在Mutex中:

use mysql::*;
use std::sync::Mutex;

fn some_fn() {
    lazy_static! {
        static ref CONNECTION: Mutex<Conn> = Mutex::new(Conn::new("mysql://root:password@127.0.0.1:3306/mydb?prefer_socket=false").unwrap());
    }
}
  

如果我的程序不是多线程的并且我使用非线程安全类型?

总是建议不要使用全局变量,线程。而是在程序的顶部创建Conn并将对它的引用传递到所有函数中。